3 * https://www.mediawiki.org/wiki/OOjs_UI
5 * Copyright 2011–2015 OOjs UI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: 2015-12-08T21:43:47Z
16 * Namespace for all classes, static methods and static properties.
53 * Generate a unique ID for element
55 * @return {String} [id]
57 OO.ui.generateElementId = function () {
59 return 'oojsui-' + OO.ui.elementId;
63 * Check if an element is focusable.
64 * Inspired from :focusable in jQueryUI v1.11.4 - 2015-04-14
66 * @param {jQuery} element Element to test
69 OO.ui.isFocusableElement = function ( $element ) {
71 element = $element[ 0 ];
73 // Anything disabled is not focusable
74 if ( element.disabled ) {
78 // Check if the element is visible
80 // This is quicker than calling $element.is( ':visible' )
81 $.expr.filters.visible( element ) &&
82 // Check that all parents are visible
83 !$element.parents().addBack().filter( function () {
84 return $.css( this, 'visibility' ) === 'hidden';
90 // Check if the element is ContentEditable, which is the string 'true'
91 if ( element.contentEditable === 'true' ) {
95 // Anything with a non-negative numeric tabIndex is focusable.
96 // Use .prop to avoid browser bugs
97 if ( $element.prop( 'tabIndex' ) >= 0 ) {
101 // Some element types are naturally focusable
102 // (indexOf is much faster than regex in Chrome and about the
103 // same in FF: https://jsperf.com/regex-vs-indexof-array2)
104 nodeName = element.nodeName.toLowerCase();
105 if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName ) !== -1 ) {
109 // Links and areas are focusable if they have an href
110 if ( ( nodeName === 'a' || nodeName === 'area' ) && $element.attr( 'href' ) !== undefined ) {
118 * Find a focusable child
120 * @param {jQuery} $container Container to search in
121 * @param {boolean} [backwards] Search backwards
122 * @return {jQuery} Focusable child, an empty jQuery object if none found
124 OO.ui.findFocusable = function ( $container, backwards ) {
125 var $focusable = $( [] ),
126 // $focusableCandidates is a superset of things that
127 // could get matched by isFocusableElement
128 $focusableCandidates = $container
129 .find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' );
132 $focusableCandidates = Array.prototype.reverse.call( $focusableCandidates );
135 $focusableCandidates.each( function () {
136 var $this = $( this );
137 if ( OO.ui.isFocusableElement( $this ) ) {
146 * Get the user's language and any fallback languages.
148 * These language codes are used to localize user interface elements in the user's language.
150 * In environments that provide a localization system, this function should be overridden to
151 * return the user's language(s). The default implementation returns English (en) only.
153 * @return {string[]} Language codes, in descending order of priority
155 OO.ui.getUserLanguages = function () {
160 * Get a value in an object keyed by language code.
162 * @param {Object.<string,Mixed>} obj Object keyed by language code
163 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
164 * @param {string} [fallback] Fallback code, used if no matching language can be found
165 * @return {Mixed} Local value
167 OO.ui.getLocalValue = function ( obj, lang, fallback ) {
170 // Requested language
174 // Known user language
175 langs = OO.ui.getUserLanguages();
176 for ( i = 0, len = langs.length; i < len; i++ ) {
183 if ( obj[ fallback ] ) {
184 return obj[ fallback ];
186 // First existing language
187 for ( lang in obj ) {
195 * Check if a node is contained within another node
197 * Similar to jQuery#contains except a list of containers can be supplied
198 * and a boolean argument allows you to include the container in the match list
200 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
201 * @param {HTMLElement} contained Node to find
202 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
203 * @return {boolean} The node is in the list of target nodes
205 OO.ui.contains = function ( containers, contained, matchContainers ) {
207 if ( !Array.isArray( containers ) ) {
208 containers = [ containers ];
210 for ( i = containers.length - 1; i >= 0; i-- ) {
211 if ( ( matchContainers && contained === containers[ i ] ) || $.contains( containers[ i ], contained ) ) {
219 * Return a function, that, as long as it continues to be invoked, will not
220 * be triggered. The function will be called after it stops being called for
221 * N milliseconds. If `immediate` is passed, trigger the function on the
222 * leading edge, instead of the trailing.
224 * Ported from: http://underscorejs.org/underscore.js
226 * @param {Function} func
227 * @param {number} wait
228 * @param {boolean} immediate
231 OO.ui.debounce = function ( func, wait, immediate ) {
236 later = function () {
239 func.apply( context, args );
242 if ( immediate && !timeout ) {
243 func.apply( context, args );
245 clearTimeout( timeout );
246 timeout = setTimeout( later, wait );
251 * Proxy for `node.addEventListener( eventName, handler, true )`, if the browser supports it.
252 * Otherwise falls back to non-capturing event listeners.
254 * @param {HTMLElement} node
255 * @param {string} eventName
256 * @param {Function} handler
258 OO.ui.addCaptureEventListener = function ( node, eventName, handler ) {
259 if ( node.addEventListener ) {
260 node.addEventListener( eventName, handler, true );
262 node.attachEvent( 'on' + eventName, handler );
267 * Proxy for `node.removeEventListener( eventName, handler, true )`, if the browser supports it.
268 * Otherwise falls back to non-capturing event listeners.
270 * @param {HTMLElement} node
271 * @param {string} eventName
272 * @param {Function} handler
274 OO.ui.removeCaptureEventListener = function ( node, eventName, handler ) {
275 if ( node.addEventListener ) {
276 node.removeEventListener( eventName, handler, true );
278 node.detachEvent( 'on' + eventName, handler );
283 * Reconstitute a JavaScript object corresponding to a widget created by
284 * the PHP implementation.
286 * This is an alias for `OO.ui.Element.static.infuse()`.
288 * @param {string|HTMLElement|jQuery} idOrNode
289 * A DOM id (if a string) or node for the widget to infuse.
290 * @return {OO.ui.Element}
291 * The `OO.ui.Element` corresponding to this (infusable) document node.
293 OO.ui.infuse = function ( idOrNode ) {
294 return OO.ui.Element.static.infuse( idOrNode );
299 * Message store for the default implementation of OO.ui.msg
301 * Environments that provide a localization system should not use this, but should override
302 * OO.ui.msg altogether.
307 // Tool tip for a button that moves items in a list down one place
308 'ooui-outline-control-move-down': 'Move item down',
309 // Tool tip for a button that moves items in a list up one place
310 'ooui-outline-control-move-up': 'Move item up',
311 // Tool tip for a button that removes items from a list
312 'ooui-outline-control-remove': 'Remove item',
313 // Label for the toolbar group that contains a list of all other available tools
314 'ooui-toolbar-more': 'More',
315 // Label for the fake tool that expands the full list of tools in a toolbar group
316 'ooui-toolgroup-expand': 'More',
317 // Label for the fake tool that collapses the full list of tools in a toolbar group
318 'ooui-toolgroup-collapse': 'Fewer',
319 // Default label for the accept button of a confirmation dialog
320 'ooui-dialog-message-accept': 'OK',
321 // Default label for the reject button of a confirmation dialog
322 'ooui-dialog-message-reject': 'Cancel',
323 // Title for process dialog error description
324 'ooui-dialog-process-error': 'Something went wrong',
325 // Label for process dialog dismiss error button, visible when describing errors
326 'ooui-dialog-process-dismiss': 'Dismiss',
327 // Label for process dialog retry action button, visible when describing only recoverable errors
328 'ooui-dialog-process-retry': 'Try again',
329 // Label for process dialog retry action button, visible when describing only warnings
330 'ooui-dialog-process-continue': 'Continue',
331 // Label for the file selection widget's select file button
332 'ooui-selectfile-button-select': 'Select a file',
333 // Label for the file selection widget if file selection is not supported
334 'ooui-selectfile-not-supported': 'File selection is not supported',
335 // Label for the file selection widget when no file is currently selected
336 'ooui-selectfile-placeholder': 'No file is selected',
337 // Label for the file selection widget's drop target
338 'ooui-selectfile-dragdrop-placeholder': 'Drop file here'
342 * Get a localized message.
344 * In environments that provide a localization system, this function should be overridden to
345 * return the message translated in the user's language. The default implementation always returns
348 * After the message key, message parameters may optionally be passed. In the default implementation,
349 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
350 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
351 * they support unnamed, ordered message parameters.
353 * @param {string} key Message key
354 * @param {Mixed...} [params] Message parameters
355 * @return {string} Translated message with parameters substituted
357 OO.ui.msg = function ( key ) {
358 var message = messages[ key ],
359 params = Array.prototype.slice.call( arguments, 1 );
360 if ( typeof message === 'string' ) {
361 // Perform $1 substitution
362 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
363 var i = parseInt( n, 10 );
364 return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n;
367 // Return placeholder if message not found
368 message = '[' + key + ']';
375 * Package a message and arguments for deferred resolution.
377 * Use this when you are statically specifying a message and the message may not yet be present.
379 * @param {string} key Message key
380 * @param {Mixed...} [params] Message parameters
381 * @return {Function} Function that returns the resolved message when executed
383 OO.ui.deferMsg = function () {
384 var args = arguments;
386 return OO.ui.msg.apply( OO.ui, args );
393 * If the message is a function it will be executed, otherwise it will pass through directly.
395 * @param {Function|string} msg Deferred message, or message text
396 * @return {string} Resolved message
398 OO.ui.resolveMsg = function ( msg ) {
399 if ( $.isFunction( msg ) ) {
406 * @param {string} url
409 OO.ui.isSafeUrl = function ( url ) {
411 // Keep in sync with php/Tag.php
413 'bitcoin:', 'ftp:', 'ftps:', 'geo:', 'git:', 'gopher:', 'http:', 'https:', 'irc:', 'ircs:',
414 'magnet:', 'mailto:', 'mms:', 'news:', 'nntp:', 'redis:', 'sftp:', 'sip:', 'sips:', 'sms:', 'ssh:',
415 'svn:', 'tel:', 'telnet:', 'urn:', 'worldwind:', 'xmpp:'
418 if ( url.indexOf( ':' ) === -1 ) {
423 protocol = url.split( ':', 1 )[ 0 ] + ':';
424 if ( !protocol.match( /^([A-za-z0-9\+\.\-])+:/ ) ) {
425 // Not a valid protocol, safe
429 // Safe if in the whitelist
430 return whitelist.indexOf( protocol ) !== -1;
434 * Lazy-initialize and return a global OO.ui.WindowManager instance, used by OO.ui.alert and
438 * @return {OO.ui.WindowManager}
440 OO.ui.getWindowManager = function () {
441 if ( !OO.ui.windowManager ) {
442 OO.ui.windowManager = new OO.ui.WindowManager();
443 $( 'body' ).append( OO.ui.windowManager.$element );
444 OO.ui.windowManager.addWindows( {
445 messageDialog: new OO.ui.MessageDialog()
448 return OO.ui.windowManager;
452 * Display a quick modal alert dialog, using a OO.ui.MessageDialog. While the dialog is open, the
453 * rest of the page will be dimmed out and the user won't be able to interact with it. The dialog
454 * has only one action button, labelled "OK", clicking it will simply close the dialog.
456 * A window manager is created automatically when this function is called for the first time.
459 * OO.ui.alert( 'Something happened!' ).done( function () {
460 * console.log( 'User closed the dialog.' );
463 * @param {jQuery|string} text Message text to display
464 * @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess
465 * @return {jQuery.Promise} Promise resolved when the user closes the dialog
467 OO.ui.alert = function ( text, options ) {
468 return OO.ui.getWindowManager().openWindow( 'messageDialog', $.extend( {
471 actions: [ OO.ui.MessageDialog.static.actions[ 0 ] ]
472 }, options ) ).then( function ( opened ) {
473 return opened.then( function ( closing ) {
474 return closing.then( function () {
475 return $.Deferred().resolve();
482 * Display a quick modal confirmation dialog, using a OO.ui.MessageDialog. While the dialog is open,
483 * the rest of the page will be dimmed out and the user won't be able to interact with it. The
484 * dialog has two action buttons, one to confirm an operation (labelled "OK") and one to cancel it
485 * (labelled "Cancel").
487 * A window manager is created automatically when this function is called for the first time.
490 * OO.ui.confirm( 'Are you sure?' ).done( function ( confirmed ) {
492 * console.log( 'User clicked "OK"!' );
494 * console.log( 'User clicked "Cancel" or closed the dialog.' );
498 * @param {jQuery|string} text Message text to display
499 * @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess
500 * @return {jQuery.Promise} Promise resolved when the user closes the dialog. If the user chose to
501 * confirm, the promise will resolve to boolean `true`; otherwise, it will resolve to boolean
504 OO.ui.confirm = function ( text, options ) {
505 return OO.ui.getWindowManager().openWindow( 'messageDialog', $.extend( {
508 }, options ) ).then( function ( opened ) {
509 return opened.then( function ( closing ) {
510 return closing.then( function ( data ) {
511 return $.Deferred().resolve( !!( data && data.action === 'accept' ) );
522 * Namespace for OOjs UI mixins.
524 * Mixins are named according to the type of object they are intended to
525 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
526 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
527 * is intended to be mixed in to an instance of OO.ui.Widget.
535 * PendingElement is a mixin that is used to create elements that notify users that something is happening
536 * and that they should wait before proceeding. The pending state is visually represented with a pending
537 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
538 * field of a {@link OO.ui.TextInputWidget text input widget}.
540 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
541 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
542 * in process dialogs.
545 * function MessageDialog( config ) {
546 * MessageDialog.parent.call( this, config );
548 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
550 * MessageDialog.static.actions = [
551 * { action: 'save', label: 'Done', flags: 'primary' },
552 * { label: 'Cancel', flags: 'safe' }
555 * MessageDialog.prototype.initialize = function () {
556 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
557 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
558 * 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>' );
559 * this.$body.append( this.content.$element );
561 * MessageDialog.prototype.getBodyHeight = function () {
564 * MessageDialog.prototype.getActionProcess = function ( action ) {
566 * if ( action === 'save' ) {
567 * dialog.getActions().get({actions: 'save'})[0].pushPending();
568 * return new OO.ui.Process()
570 * .next( function () {
571 * dialog.getActions().get({actions: 'save'})[0].popPending();
574 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
577 * var windowManager = new OO.ui.WindowManager();
578 * $( 'body' ).append( windowManager.$element );
580 * var dialog = new MessageDialog();
581 * windowManager.addWindows( [ dialog ] );
582 * windowManager.openWindow( dialog );
588 * @param {Object} [config] Configuration options
589 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
591 OO.ui.mixin.PendingElement = function OoUiMixinPendingElement( config ) {
592 // Configuration initialization
593 config = config || {};
597 this.$pending = null;
600 this.setPendingElement( config.$pending || this.$element );
605 OO.initClass( OO.ui.mixin.PendingElement );
610 * Set the pending element (and clean up any existing one).
612 * @param {jQuery} $pending The element to set to pending.
614 OO.ui.mixin.PendingElement.prototype.setPendingElement = function ( $pending ) {
615 if ( this.$pending ) {
616 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
619 this.$pending = $pending;
620 if ( this.pending > 0 ) {
621 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
626 * Check if an element is pending.
628 * @return {boolean} Element is pending
630 OO.ui.mixin.PendingElement.prototype.isPending = function () {
631 return !!this.pending;
635 * Increase the pending counter. The pending state will remain active until the counter is zero
636 * (i.e., the number of calls to #pushPending and #popPending is the same).
640 OO.ui.mixin.PendingElement.prototype.pushPending = function () {
641 if ( this.pending === 0 ) {
642 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
643 this.updateThemeClasses();
651 * Decrease the pending counter. The pending state will remain active until the counter is zero
652 * (i.e., the number of calls to #pushPending and #popPending is the same).
656 OO.ui.mixin.PendingElement.prototype.popPending = function () {
657 if ( this.pending === 1 ) {
658 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
659 this.updateThemeClasses();
661 this.pending = Math.max( 0, this.pending - 1 );
667 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
668 * Actions can be made available for specific contexts (modes) and circumstances
669 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
671 * ActionSets contain two types of actions:
673 * - 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.
674 * - Other: Other actions include all non-special visible actions.
676 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
679 * // Example: An action set used in a process dialog
680 * function MyProcessDialog( config ) {
681 * MyProcessDialog.parent.call( this, config );
683 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
684 * MyProcessDialog.static.title = 'An action set in a process dialog';
685 * // An action set that uses modes ('edit' and 'help' mode, in this example).
686 * MyProcessDialog.static.actions = [
687 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
688 * { action: 'help', modes: 'edit', label: 'Help' },
689 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
690 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
693 * MyProcessDialog.prototype.initialize = function () {
694 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
695 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
696 * 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>' );
697 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
698 * 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>' );
699 * this.stackLayout = new OO.ui.StackLayout( {
700 * items: [ this.panel1, this.panel2 ]
702 * this.$body.append( this.stackLayout.$element );
704 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
705 * return MyProcessDialog.parent.prototype.getSetupProcess.call( this, data )
706 * .next( function () {
707 * this.actions.setMode( 'edit' );
710 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
711 * if ( action === 'help' ) {
712 * this.actions.setMode( 'help' );
713 * this.stackLayout.setItem( this.panel2 );
714 * } else if ( action === 'back' ) {
715 * this.actions.setMode( 'edit' );
716 * this.stackLayout.setItem( this.panel1 );
717 * } else if ( action === 'continue' ) {
719 * return new OO.ui.Process( function () {
723 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
725 * MyProcessDialog.prototype.getBodyHeight = function () {
726 * return this.panel1.$element.outerHeight( true );
728 * var windowManager = new OO.ui.WindowManager();
729 * $( 'body' ).append( windowManager.$element );
730 * var dialog = new MyProcessDialog( {
733 * windowManager.addWindows( [ dialog ] );
734 * windowManager.openWindow( dialog );
736 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
740 * @mixins OO.EventEmitter
743 * @param {Object} [config] Configuration options
745 OO.ui.ActionSet = function OoUiActionSet( config ) {
746 // Configuration initialization
747 config = config || {};
749 // Mixin constructors
750 OO.EventEmitter.call( this );
755 actions: 'getAction',
759 this.categorized = {};
762 this.organized = false;
763 this.changing = false;
764 this.changed = false;
769 OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter );
771 /* Static Properties */
774 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
775 * header of a {@link OO.ui.ProcessDialog process dialog}.
776 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
778 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
785 OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ];
792 * A 'click' event is emitted when an action is clicked.
794 * @param {OO.ui.ActionWidget} action Action that was clicked
800 * A 'resize' event is emitted when an action widget is resized.
802 * @param {OO.ui.ActionWidget} action Action that was resized
808 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
810 * @param {OO.ui.ActionWidget[]} added Actions added
816 * A 'remove' event is emitted when actions are {@link #method-remove removed}
817 * or {@link #clear cleared}.
819 * @param {OO.ui.ActionWidget[]} added Actions removed
825 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
826 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
833 * Handle action change events.
838 OO.ui.ActionSet.prototype.onActionChange = function () {
839 this.organized = false;
840 if ( this.changing ) {
843 this.emit( 'change' );
848 * Check if an action is one of the special actions.
850 * @param {OO.ui.ActionWidget} action Action to check
851 * @return {boolean} Action is special
853 OO.ui.ActionSet.prototype.isSpecial = function ( action ) {
856 for ( flag in this.special ) {
857 if ( action === this.special[ flag ] ) {
866 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
869 * @param {Object} [filters] Filters to use, omit to get all actions
870 * @param {string|string[]} [filters.actions] Actions that action widgets must have
871 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
872 * @param {string|string[]} [filters.modes] Modes that action widgets must have
873 * @param {boolean} [filters.visible] Action widgets must be visible
874 * @param {boolean} [filters.disabled] Action widgets must be disabled
875 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
877 OO.ui.ActionSet.prototype.get = function ( filters ) {
878 var i, len, list, category, actions, index, match, matches;
883 // Collect category candidates
885 for ( category in this.categorized ) {
886 list = filters[ category ];
888 if ( !Array.isArray( list ) ) {
891 for ( i = 0, len = list.length; i < len; i++ ) {
892 actions = this.categorized[ category ][ list[ i ] ];
893 if ( Array.isArray( actions ) ) {
894 matches.push.apply( matches, actions );
899 // Remove by boolean filters
900 for ( i = 0, len = matches.length; i < len; i++ ) {
901 match = matches[ i ];
903 ( filters.visible !== undefined && match.isVisible() !== filters.visible ) ||
904 ( filters.disabled !== undefined && match.isDisabled() !== filters.disabled )
906 matches.splice( i, 1 );
912 for ( i = 0, len = matches.length; i < len; i++ ) {
913 match = matches[ i ];
914 index = matches.lastIndexOf( match );
915 while ( index !== i ) {
916 matches.splice( index, 1 );
918 index = matches.lastIndexOf( match );
923 return this.list.slice();
927 * Get 'special' actions.
929 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
930 * Special flags can be configured in subclasses by changing the static #specialFlags property.
932 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
934 OO.ui.ActionSet.prototype.getSpecial = function () {
936 return $.extend( {}, this.special );
940 * Get 'other' actions.
942 * Other actions include all non-special visible action widgets.
944 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
946 OO.ui.ActionSet.prototype.getOthers = function () {
948 return this.others.slice();
952 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
953 * to be available in the specified mode will be made visible. All other actions will be hidden.
955 * @param {string} mode The mode. Only actions configured to be available in the specified
956 * mode will be made visible.
961 OO.ui.ActionSet.prototype.setMode = function ( mode ) {
964 this.changing = true;
965 for ( i = 0, len = this.list.length; i < len; i++ ) {
966 action = this.list[ i ];
967 action.toggle( action.hasMode( mode ) );
970 this.organized = false;
971 this.changing = false;
972 this.emit( 'change' );
978 * Set the abilities of the specified actions.
980 * Action widgets that are configured with the specified actions will be enabled
981 * or disabled based on the boolean values specified in the `actions`
984 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
985 * values that indicate whether or not the action should be enabled.
988 OO.ui.ActionSet.prototype.setAbilities = function ( actions ) {
989 var i, len, action, item;
991 for ( i = 0, len = this.list.length; i < len; i++ ) {
992 item = this.list[ i ];
993 action = item.getAction();
994 if ( actions[ action ] !== undefined ) {
995 item.setDisabled( !actions[ action ] );
1003 * Executes a function once per action.
1005 * When making changes to multiple actions, use this method instead of iterating over the actions
1006 * manually to defer emitting a #change event until after all actions have been changed.
1008 * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get
1009 * @param {Function} callback Callback to run for each action; callback is invoked with three
1010 * arguments: the action, the action's index, the list of actions being iterated over
1013 OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) {
1014 this.changed = false;
1015 this.changing = true;
1016 this.get( filter ).forEach( callback );
1017 this.changing = false;
1018 if ( this.changed ) {
1019 this.emit( 'change' );
1026 * Add action widgets to the action set.
1028 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
1033 OO.ui.ActionSet.prototype.add = function ( actions ) {
1036 this.changing = true;
1037 for ( i = 0, len = actions.length; i < len; i++ ) {
1038 action = actions[ i ];
1039 action.connect( this, {
1040 click: [ 'emit', 'click', action ],
1041 resize: [ 'emit', 'resize', action ],
1042 toggle: [ 'onActionChange' ]
1044 this.list.push( action );
1046 this.organized = false;
1047 this.emit( 'add', actions );
1048 this.changing = false;
1049 this.emit( 'change' );
1055 * Remove action widgets from the set.
1057 * To remove all actions, you may wish to use the #clear method instead.
1059 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
1064 OO.ui.ActionSet.prototype.remove = function ( actions ) {
1065 var i, len, index, action;
1067 this.changing = true;
1068 for ( i = 0, len = actions.length; i < len; i++ ) {
1069 action = actions[ i ];
1070 index = this.list.indexOf( action );
1071 if ( index !== -1 ) {
1072 action.disconnect( this );
1073 this.list.splice( index, 1 );
1076 this.organized = false;
1077 this.emit( 'remove', actions );
1078 this.changing = false;
1079 this.emit( 'change' );
1085 * Remove all action widets from the set.
1087 * To remove only specified actions, use the {@link #method-remove remove} method instead.
1093 OO.ui.ActionSet.prototype.clear = function () {
1095 removed = this.list.slice();
1097 this.changing = true;
1098 for ( i = 0, len = this.list.length; i < len; i++ ) {
1099 action = this.list[ i ];
1100 action.disconnect( this );
1105 this.organized = false;
1106 this.emit( 'remove', removed );
1107 this.changing = false;
1108 this.emit( 'change' );
1116 * This is called whenever organized information is requested. It will only reorganize the actions
1117 * if something has changed since the last time it ran.
1122 OO.ui.ActionSet.prototype.organize = function () {
1123 var i, iLen, j, jLen, flag, action, category, list, item, special,
1124 specialFlags = this.constructor.static.specialFlags;
1126 if ( !this.organized ) {
1127 this.categorized = {};
1130 for ( i = 0, iLen = this.list.length; i < iLen; i++ ) {
1131 action = this.list[ i ];
1132 if ( action.isVisible() ) {
1133 // Populate categories
1134 for ( category in this.categories ) {
1135 if ( !this.categorized[ category ] ) {
1136 this.categorized[ category ] = {};
1138 list = action[ this.categories[ category ] ]();
1139 if ( !Array.isArray( list ) ) {
1142 for ( j = 0, jLen = list.length; j < jLen; j++ ) {
1144 if ( !this.categorized[ category ][ item ] ) {
1145 this.categorized[ category ][ item ] = [];
1147 this.categorized[ category ][ item ].push( action );
1150 // Populate special/others
1152 for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) {
1153 flag = specialFlags[ j ];
1154 if ( !this.special[ flag ] && action.hasFlag( flag ) ) {
1155 this.special[ flag ] = action;
1161 this.others.push( action );
1165 this.organized = true;
1172 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
1173 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
1174 * connected to them and can't be interacted with.
1180 * @param {Object} [config] Configuration options
1181 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
1182 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
1184 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
1185 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
1186 * @cfg {string} [text] Text to insert
1187 * @cfg {Array} [content] An array of content elements to append (after #text).
1188 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
1189 * Instances of OO.ui.Element will have their $element appended.
1190 * @cfg {jQuery} [$content] Content elements to append (after #text).
1191 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
1192 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
1193 * Data can also be specified with the #setData method.
1195 OO.ui.Element = function OoUiElement( config ) {
1196 // Configuration initialization
1197 config = config || {};
1201 this.visible = true;
1202 this.data = config.data;
1203 this.$element = config.$element ||
1204 $( document.createElement( this.getTagName() ) );
1205 this.elementGroup = null;
1206 this.debouncedUpdateThemeClassesHandler = OO.ui.debounce( this.debouncedUpdateThemeClasses );
1209 if ( Array.isArray( config.classes ) ) {
1210 this.$element.addClass( config.classes.join( ' ' ) );
1213 this.$element.attr( 'id', config.id );
1215 if ( config.text ) {
1216 this.$element.text( config.text );
1218 if ( config.content ) {
1219 // The `content` property treats plain strings as text; use an
1220 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
1221 // appropriate $element appended.
1222 this.$element.append( config.content.map( function ( v ) {
1223 if ( typeof v === 'string' ) {
1224 // Escape string so it is properly represented in HTML.
1225 return document.createTextNode( v );
1226 } else if ( v instanceof OO.ui.HtmlSnippet ) {
1228 return v.toString();
1229 } else if ( v instanceof OO.ui.Element ) {
1235 if ( config.$content ) {
1236 // The `$content` property treats plain strings as HTML.
1237 this.$element.append( config.$content );
1243 OO.initClass( OO.ui.Element );
1245 /* Static Properties */
1248 * The name of the HTML tag used by the element.
1250 * The static value may be ignored if the #getTagName method is overridden.
1254 * @property {string}
1256 OO.ui.Element.static.tagName = 'div';
1258 /* Static Methods */
1261 * Reconstitute a JavaScript object corresponding to a widget created
1262 * by the PHP implementation.
1264 * @param {string|HTMLElement|jQuery} idOrNode
1265 * A DOM id (if a string) or node for the widget to infuse.
1266 * @return {OO.ui.Element}
1267 * The `OO.ui.Element` corresponding to this (infusable) document node.
1268 * For `Tag` objects emitted on the HTML side (used occasionally for content)
1269 * the value returned is a newly-created Element wrapping around the existing
1272 OO.ui.Element.static.infuse = function ( idOrNode ) {
1273 var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, false );
1274 // Verify that the type matches up.
1275 // FIXME: uncomment after T89721 is fixed (see T90929)
1277 if ( !( obj instanceof this['class'] ) ) {
1278 throw new Error( 'Infusion type mismatch!' );
1285 * Implementation helper for `infuse`; skips the type check and has an
1286 * extra property so that only the top-level invocation touches the DOM.
1288 * @param {string|HTMLElement|jQuery} idOrNode
1289 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
1290 * when the top-level widget of this infusion is inserted into DOM,
1291 * replacing the original node; or false for top-level invocation.
1292 * @return {OO.ui.Element}
1294 OO.ui.Element.static.unsafeInfuse = function ( idOrNode, domPromise ) {
1295 // look for a cached result of a previous infusion.
1296 var id, $elem, data, cls, parts, parent, obj, top, state;
1297 if ( typeof idOrNode === 'string' ) {
1299 $elem = $( document.getElementById( id ) );
1301 $elem = $( idOrNode );
1302 id = $elem.attr( 'id' );
1304 if ( !$elem.length ) {
1305 throw new Error( 'Widget not found: ' + id );
1307 data = $elem.data( 'ooui-infused' ) || $elem[ 0 ].oouiInfused;
1310 if ( data === true ) {
1311 throw new Error( 'Circular dependency! ' + id );
1315 data = $elem.attr( 'data-ooui' );
1317 throw new Error( 'No infusion data found: ' + id );
1320 data = $.parseJSON( data );
1324 if ( !( data && data._ ) ) {
1325 throw new Error( 'No valid infusion data found: ' + id );
1327 if ( data._ === 'Tag' ) {
1328 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
1329 return new OO.ui.Element( { $element: $elem } );
1331 parts = data._.split( '.' );
1332 cls = OO.getProp.apply( OO, [ window ].concat( parts ) );
1333 if ( cls === undefined ) {
1334 // The PHP output might be old and not including the "OO.ui" prefix
1335 // TODO: Remove this back-compat after next major release
1336 cls = OO.getProp.apply( OO, [ OO.ui ].concat( parts ) );
1337 if ( cls === undefined ) {
1338 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
1342 // Verify that we're creating an OO.ui.Element instance
1343 parent = cls.parent;
1345 while ( parent !== undefined ) {
1346 if ( parent === OO.ui.Element ) {
1351 parent = parent.parent;
1354 if ( parent !== OO.ui.Element ) {
1355 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
1358 if ( domPromise === false ) {
1360 domPromise = top.promise();
1362 $elem.data( 'ooui-infused', true ); // prevent loops
1363 data.id = id; // implicit
1364 data = OO.copy( data, null, function deserialize( value ) {
1365 if ( OO.isPlainObject( value ) ) {
1367 return OO.ui.Element.static.unsafeInfuse( value.tag, domPromise );
1370 return new OO.ui.HtmlSnippet( value.html );
1374 // allow widgets to reuse parts of the DOM
1375 data = cls.static.reusePreInfuseDOM( $elem[ 0 ], data );
1376 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
1377 state = cls.static.gatherPreInfuseState( $elem[ 0 ], data );
1379 // jscs:disable requireCapitalizedConstructors
1380 obj = new cls( data );
1381 // jscs:enable requireCapitalizedConstructors
1382 // now replace old DOM with this new DOM.
1384 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
1385 // so only mutate the DOM if we need to.
1386 if ( $elem[ 0 ] !== obj.$element[ 0 ] ) {
1387 $elem.replaceWith( obj.$element );
1388 // This element is now gone from the DOM, but if anyone is holding a reference to it,
1389 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
1390 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
1391 $elem[ 0 ].oouiInfused = obj;
1395 obj.$element.data( 'ooui-infused', obj );
1396 // set the 'data-ooui' attribute so we can identify infused widgets
1397 obj.$element.attr( 'data-ooui', '' );
1398 // restore dynamic state after the new element is inserted into DOM
1399 domPromise.done( obj.restorePreInfuseState.bind( obj, state ) );
1404 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
1406 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
1407 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
1408 * constructor, which will be given the enhanced config.
1411 * @param {HTMLElement} node
1412 * @param {Object} config
1415 OO.ui.Element.static.reusePreInfuseDOM = function ( node, config ) {
1420 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of a HTML DOM node
1421 * (and its children) that represent an Element of the same class and the given configuration,
1422 * generated by the PHP implementation.
1424 * This method is called just before `node` is detached from the DOM. The return value of this
1425 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
1426 * is inserted into DOM to replace `node`.
1429 * @param {HTMLElement} node
1430 * @param {Object} config
1433 OO.ui.Element.static.gatherPreInfuseState = function () {
1438 * Get a jQuery function within a specific document.
1441 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1442 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1444 * @return {Function} Bound jQuery function
1446 OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
1447 function wrapper( selector ) {
1448 return $( selector, wrapper.context );
1451 wrapper.context = this.getDocument( context );
1454 wrapper.$iframe = $iframe;
1461 * Get the document of an element.
1464 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1465 * @return {HTMLDocument|null} Document object
1467 OO.ui.Element.static.getDocument = function ( obj ) {
1468 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1469 return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
1470 // Empty jQuery selections might have a context
1473 obj.ownerDocument ||
1477 ( obj.nodeType === 9 && obj ) ||
1482 * Get the window of an element or document.
1485 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1486 * @return {Window} Window object
1488 OO.ui.Element.static.getWindow = function ( obj ) {
1489 var doc = this.getDocument( obj );
1491 // Standard Document.defaultView is IE9+
1492 return doc.parentWindow || doc.defaultView;
1496 * Get the direction of an element or document.
1499 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1500 * @return {string} Text direction, either 'ltr' or 'rtl'
1502 OO.ui.Element.static.getDir = function ( obj ) {
1505 if ( obj instanceof jQuery ) {
1508 isDoc = obj.nodeType === 9;
1509 isWin = obj.document !== undefined;
1510 if ( isDoc || isWin ) {
1516 return $( obj ).css( 'direction' );
1520 * Get the offset between two frames.
1522 * TODO: Make this function not use recursion.
1525 * @param {Window} from Window of the child frame
1526 * @param {Window} [to=window] Window of the parent frame
1527 * @param {Object} [offset] Offset to start with, used internally
1528 * @return {Object} Offset object, containing left and top properties
1530 OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
1531 var i, len, frames, frame, rect;
1537 offset = { top: 0, left: 0 };
1539 if ( from.parent === from ) {
1543 // Get iframe element
1544 frames = from.parent.document.getElementsByTagName( 'iframe' );
1545 for ( i = 0, len = frames.length; i < len; i++ ) {
1546 if ( frames[ i ].contentWindow === from ) {
1547 frame = frames[ i ];
1552 // Recursively accumulate offset values
1554 rect = frame.getBoundingClientRect();
1555 offset.left += rect.left;
1556 offset.top += rect.top;
1557 if ( from !== to ) {
1558 this.getFrameOffset( from.parent, offset );
1565 * Get the offset between two elements.
1567 * The two elements may be in a different frame, but in that case the frame $element is in must
1568 * be contained in the frame $anchor is in.
1571 * @param {jQuery} $element Element whose position to get
1572 * @param {jQuery} $anchor Element to get $element's position relative to
1573 * @return {Object} Translated position coordinates, containing top and left properties
1575 OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
1576 var iframe, iframePos,
1577 pos = $element.offset(),
1578 anchorPos = $anchor.offset(),
1579 elementDocument = this.getDocument( $element ),
1580 anchorDocument = this.getDocument( $anchor );
1582 // If $element isn't in the same document as $anchor, traverse up
1583 while ( elementDocument !== anchorDocument ) {
1584 iframe = elementDocument.defaultView.frameElement;
1586 throw new Error( '$element frame is not contained in $anchor frame' );
1588 iframePos = $( iframe ).offset();
1589 pos.left += iframePos.left;
1590 pos.top += iframePos.top;
1591 elementDocument = iframe.ownerDocument;
1593 pos.left -= anchorPos.left;
1594 pos.top -= anchorPos.top;
1599 * Get element border sizes.
1602 * @param {HTMLElement} el Element to measure
1603 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1605 OO.ui.Element.static.getBorders = function ( el ) {
1606 var doc = el.ownerDocument,
1608 // Standard Document.defaultView is IE9+
1609 win = doc.parentWindow || doc.defaultView,
1610 style = win && win.getComputedStyle ?
1611 win.getComputedStyle( el, null ) :
1613 // Standard getComputedStyle() is IE9+
1616 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
1617 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
1618 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
1619 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
1630 * Get dimensions of an element or window.
1633 * @param {HTMLElement|Window} el Element to measure
1634 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1636 OO.ui.Element.static.getDimensions = function ( el ) {
1638 doc = el.ownerDocument || el.document,
1640 // Standard Document.defaultView is IE9+
1641 win = doc.parentWindow || doc.defaultView;
1643 if ( win === el || el === doc.documentElement ) {
1646 borders: { top: 0, left: 0, bottom: 0, right: 0 },
1648 top: $win.scrollTop(),
1649 left: $win.scrollLeft()
1651 scrollbar: { right: 0, bottom: 0 },
1655 bottom: $win.innerHeight(),
1656 right: $win.innerWidth()
1662 borders: this.getBorders( el ),
1664 top: $el.scrollTop(),
1665 left: $el.scrollLeft()
1668 right: $el.innerWidth() - el.clientWidth,
1669 bottom: $el.innerHeight() - el.clientHeight
1671 rect: el.getBoundingClientRect()
1677 * Get scrollable object parent
1679 * documentElement can't be used to get or set the scrollTop
1680 * property on Blink. Changing and testing its value lets us
1681 * use 'body' or 'documentElement' based on what is working.
1683 * https://code.google.com/p/chromium/issues/detail?id=303131
1686 * @param {HTMLElement} el Element to find scrollable parent for
1687 * @return {HTMLElement} Scrollable parent
1689 OO.ui.Element.static.getRootScrollableElement = function ( el ) {
1690 var scrollTop, body;
1692 if ( OO.ui.scrollableElement === undefined ) {
1693 body = el.ownerDocument.body;
1694 scrollTop = body.scrollTop;
1697 if ( body.scrollTop === 1 ) {
1698 body.scrollTop = scrollTop;
1699 OO.ui.scrollableElement = 'body';
1701 OO.ui.scrollableElement = 'documentElement';
1705 return el.ownerDocument[ OO.ui.scrollableElement ];
1709 * Get closest scrollable container.
1711 * Traverses up until either a scrollable element or the root is reached, in which case the window
1715 * @param {HTMLElement} el Element to find scrollable container for
1716 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1717 * @return {HTMLElement} Closest scrollable container
1719 OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
1721 // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
1722 props = [ 'overflow-x', 'overflow-y' ],
1723 $parent = $( el ).parent();
1725 if ( dimension === 'x' || dimension === 'y' ) {
1726 props = [ 'overflow-' + dimension ];
1729 while ( $parent.length ) {
1730 if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
1731 return $parent[ 0 ];
1735 val = $parent.css( props[ i ] );
1736 if ( val === 'auto' || val === 'scroll' ) {
1737 return $parent[ 0 ];
1740 $parent = $parent.parent();
1742 return this.getDocument( el ).body;
1746 * Scroll element into view.
1749 * @param {HTMLElement} el Element to scroll into view
1750 * @param {Object} [config] Configuration options
1751 * @param {string} [config.duration] jQuery animation duration value
1752 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1753 * to scroll in both directions
1754 * @param {Function} [config.complete] Function to call when scrolling completes
1756 OO.ui.Element.static.scrollIntoView = function ( el, config ) {
1757 var rel, anim, callback, sc, $sc, eld, scd, $win;
1759 // Configuration initialization
1760 config = config || {};
1763 callback = typeof config.complete === 'function' && config.complete;
1764 sc = this.getClosestScrollableContainer( el, config.direction );
1766 eld = this.getDimensions( el );
1767 scd = this.getDimensions( sc );
1768 $win = $( this.getWindow( el ) );
1770 // Compute the distances between the edges of el and the edges of the scroll viewport
1771 if ( $sc.is( 'html, body' ) ) {
1772 // If the scrollable container is the root, this is easy
1775 bottom: $win.innerHeight() - eld.rect.bottom,
1776 left: eld.rect.left,
1777 right: $win.innerWidth() - eld.rect.right
1780 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1782 top: eld.rect.top - ( scd.rect.top + scd.borders.top ),
1783 bottom: scd.rect.bottom - scd.borders.bottom - scd.scrollbar.bottom - eld.rect.bottom,
1784 left: eld.rect.left - ( scd.rect.left + scd.borders.left ),
1785 right: scd.rect.right - scd.borders.right - scd.scrollbar.right - eld.rect.right
1789 if ( !config.direction || config.direction === 'y' ) {
1790 if ( rel.top < 0 ) {
1791 anim.scrollTop = scd.scroll.top + rel.top;
1792 } else if ( rel.top > 0 && rel.bottom < 0 ) {
1793 anim.scrollTop = scd.scroll.top + Math.min( rel.top, -rel.bottom );
1796 if ( !config.direction || config.direction === 'x' ) {
1797 if ( rel.left < 0 ) {
1798 anim.scrollLeft = scd.scroll.left + rel.left;
1799 } else if ( rel.left > 0 && rel.right < 0 ) {
1800 anim.scrollLeft = scd.scroll.left + Math.min( rel.left, -rel.right );
1803 if ( !$.isEmptyObject( anim ) ) {
1804 $sc.stop( true ).animate( anim, config.duration || 'fast' );
1806 $sc.queue( function ( next ) {
1819 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1820 * and reserve space for them, because it probably doesn't.
1822 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1823 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1824 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1825 * and then reattach (or show) them back.
1828 * @param {HTMLElement} el Element to reconsider the scrollbars on
1830 OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
1831 var i, len, scrollLeft, scrollTop, nodes = [];
1832 // Save scroll position
1833 scrollLeft = el.scrollLeft;
1834 scrollTop = el.scrollTop;
1835 // Detach all children
1836 while ( el.firstChild ) {
1837 nodes.push( el.firstChild );
1838 el.removeChild( el.firstChild );
1841 void el.offsetHeight;
1842 // Reattach all children
1843 for ( i = 0, len = nodes.length; i < len; i++ ) {
1844 el.appendChild( nodes[ i ] );
1846 // Restore scroll position (no-op if scrollbars disappeared)
1847 el.scrollLeft = scrollLeft;
1848 el.scrollTop = scrollTop;
1854 * Toggle visibility of an element.
1856 * @param {boolean} [show] Make element visible, omit to toggle visibility
1860 OO.ui.Element.prototype.toggle = function ( show ) {
1861 show = show === undefined ? !this.visible : !!show;
1863 if ( show !== this.isVisible() ) {
1864 this.visible = show;
1865 this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
1866 this.emit( 'toggle', show );
1873 * Check if element is visible.
1875 * @return {boolean} element is visible
1877 OO.ui.Element.prototype.isVisible = function () {
1878 return this.visible;
1884 * @return {Mixed} Element data
1886 OO.ui.Element.prototype.getData = function () {
1893 * @param {Mixed} Element data
1896 OO.ui.Element.prototype.setData = function ( data ) {
1902 * Check if element supports one or more methods.
1904 * @param {string|string[]} methods Method or list of methods to check
1905 * @return {boolean} All methods are supported
1907 OO.ui.Element.prototype.supports = function ( methods ) {
1911 methods = Array.isArray( methods ) ? methods : [ methods ];
1912 for ( i = 0, len = methods.length; i < len; i++ ) {
1913 if ( $.isFunction( this[ methods[ i ] ] ) ) {
1918 return methods.length === support;
1922 * Update the theme-provided classes.
1924 * @localdoc This is called in element mixins and widget classes any time state changes.
1925 * Updating is debounced, minimizing overhead of changing multiple attributes and
1926 * guaranteeing that theme updates do not occur within an element's constructor
1928 OO.ui.Element.prototype.updateThemeClasses = function () {
1929 this.debouncedUpdateThemeClassesHandler();
1934 * @localdoc This method is called directly from the QUnit tests instead of #updateThemeClasses, to
1935 * make them synchronous.
1937 OO.ui.Element.prototype.debouncedUpdateThemeClasses = function () {
1938 OO.ui.theme.updateElementClasses( this );
1942 * Get the HTML tag name.
1944 * Override this method to base the result on instance information.
1946 * @return {string} HTML tag name
1948 OO.ui.Element.prototype.getTagName = function () {
1949 return this.constructor.static.tagName;
1953 * Check if the element is attached to the DOM
1954 * @return {boolean} The element is attached to the DOM
1956 OO.ui.Element.prototype.isElementAttached = function () {
1957 return $.contains( this.getElementDocument(), this.$element[ 0 ] );
1961 * Get the DOM document.
1963 * @return {HTMLDocument} Document object
1965 OO.ui.Element.prototype.getElementDocument = function () {
1966 // Don't cache this in other ways either because subclasses could can change this.$element
1967 return OO.ui.Element.static.getDocument( this.$element );
1971 * Get the DOM window.
1973 * @return {Window} Window object
1975 OO.ui.Element.prototype.getElementWindow = function () {
1976 return OO.ui.Element.static.getWindow( this.$element );
1980 * Get closest scrollable container.
1982 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1983 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
1987 * Get group element is in.
1989 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1991 OO.ui.Element.prototype.getElementGroup = function () {
1992 return this.elementGroup;
1996 * Set group element is in.
1998 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
2001 OO.ui.Element.prototype.setElementGroup = function ( group ) {
2002 this.elementGroup = group;
2007 * Scroll element into view.
2009 * @param {Object} [config] Configuration options
2011 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
2012 return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
2016 * Restore the pre-infusion dynamic state for this widget.
2018 * This method is called after #$element has been inserted into DOM. The parameter is the return
2019 * value of #gatherPreInfuseState.
2022 * @param {Object} state
2024 OO.ui.Element.prototype.restorePreInfuseState = function () {
2028 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
2029 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
2030 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
2031 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
2032 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
2036 * @extends OO.ui.Element
2037 * @mixins OO.EventEmitter
2040 * @param {Object} [config] Configuration options
2042 OO.ui.Layout = function OoUiLayout( config ) {
2043 // Configuration initialization
2044 config = config || {};
2046 // Parent constructor
2047 OO.ui.Layout.parent.call( this, config );
2049 // Mixin constructors
2050 OO.EventEmitter.call( this );
2053 this.$element.addClass( 'oo-ui-layout' );
2058 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
2059 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
2062 * Widgets are compositions of one or more OOjs UI elements that users can both view
2063 * and interact with. All widgets can be configured and modified via a standard API,
2064 * and their state can change dynamically according to a model.
2068 * @extends OO.ui.Element
2069 * @mixins OO.EventEmitter
2072 * @param {Object} [config] Configuration options
2073 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
2074 * appearance reflects this state.
2076 OO.ui.Widget = function OoUiWidget( config ) {
2077 // Initialize config
2078 config = $.extend( { disabled: false }, config );
2080 // Parent constructor
2081 OO.ui.Widget.parent.call( this, config );
2083 // Mixin constructors
2084 OO.EventEmitter.call( this );
2087 this.disabled = null;
2088 this.wasDisabled = null;
2091 this.$element.addClass( 'oo-ui-widget' );
2092 this.setDisabled( !!config.disabled );
2097 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
2098 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
2100 /* Static Properties */
2103 * Whether this widget will behave reasonably when wrapped in a HTML `<label>`. If this is true,
2104 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
2109 * @property {boolean}
2111 OO.ui.Widget.static.supportsSimpleLabel = false;
2118 * A 'disable' event is emitted when the disabled state of the widget changes
2119 * (i.e. on disable **and** enable).
2121 * @param {boolean} disabled Widget is disabled
2127 * A 'toggle' event is emitted when the visibility of the widget changes.
2129 * @param {boolean} visible Widget is visible
2135 * Check if the widget is disabled.
2137 * @return {boolean} Widget is disabled
2139 OO.ui.Widget.prototype.isDisabled = function () {
2140 return this.disabled;
2144 * Set the 'disabled' state of the widget.
2146 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
2148 * @param {boolean} disabled Disable widget
2151 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
2154 this.disabled = !!disabled;
2155 isDisabled = this.isDisabled();
2156 if ( isDisabled !== this.wasDisabled ) {
2157 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
2158 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
2159 this.$element.attr( 'aria-disabled', isDisabled.toString() );
2160 this.emit( 'disable', isDisabled );
2161 this.updateThemeClasses();
2163 this.wasDisabled = isDisabled;
2169 * Update the disabled state, in case of changes in parent widget.
2173 OO.ui.Widget.prototype.updateDisabled = function () {
2174 this.setDisabled( this.disabled );
2179 * A window is a container for elements that are in a child frame. They are used with
2180 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
2181 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
2182 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
2183 * the window manager will choose a sensible fallback.
2185 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
2186 * different processes are executed:
2188 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
2189 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
2192 * - {@link #getSetupProcess} method is called and its result executed
2193 * - {@link #getReadyProcess} method is called and its result executed
2195 * **opened**: The window is now open
2197 * **closing**: The closing stage begins when the window manager's
2198 * {@link OO.ui.WindowManager#closeWindow closeWindow}
2199 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
2201 * - {@link #getHoldProcess} method is called and its result executed
2202 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
2204 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
2205 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
2206 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
2207 * processing can complete. Always assume window processes are executed asynchronously.
2209 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2211 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
2215 * @extends OO.ui.Element
2216 * @mixins OO.EventEmitter
2219 * @param {Object} [config] Configuration options
2220 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
2221 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
2223 OO.ui.Window = function OoUiWindow( config ) {
2224 // Configuration initialization
2225 config = config || {};
2227 // Parent constructor
2228 OO.ui.Window.parent.call( this, config );
2230 // Mixin constructors
2231 OO.EventEmitter.call( this );
2234 this.manager = null;
2235 this.size = config.size || this.constructor.static.size;
2236 this.$frame = $( '<div>' );
2237 this.$overlay = $( '<div>' );
2238 this.$content = $( '<div>' );
2240 this.$focusTrapBefore = $( '<div>' ).prop( 'tabIndex', 0 );
2241 this.$focusTrapAfter = $( '<div>' ).prop( 'tabIndex', 0 );
2242 this.$focusTraps = this.$focusTrapBefore.add( this.$focusTrapAfter );
2245 this.$overlay.addClass( 'oo-ui-window-overlay' );
2247 .addClass( 'oo-ui-window-content' )
2248 .attr( 'tabindex', 0 );
2250 .addClass( 'oo-ui-window-frame' )
2251 .append( this.$focusTrapBefore, this.$content, this.$focusTrapAfter );
2254 .addClass( 'oo-ui-window' )
2255 .append( this.$frame, this.$overlay );
2257 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
2258 // that reference properties not initialized at that time of parent class construction
2259 // TODO: Find a better way to handle post-constructor setup
2260 this.visible = false;
2261 this.$element.addClass( 'oo-ui-element-hidden' );
2266 OO.inheritClass( OO.ui.Window, OO.ui.Element );
2267 OO.mixinClass( OO.ui.Window, OO.EventEmitter );
2269 /* Static Properties */
2272 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
2274 * The static size is used if no #size is configured during construction.
2278 * @property {string}
2280 OO.ui.Window.static.size = 'medium';
2285 * Handle mouse down events.
2288 * @param {jQuery.Event} e Mouse down event
2290 OO.ui.Window.prototype.onMouseDown = function ( e ) {
2291 // Prevent clicking on the click-block from stealing focus
2292 if ( e.target === this.$element[ 0 ] ) {
2298 * Check if the window has been initialized.
2300 * Initialization occurs when a window is added to a manager.
2302 * @return {boolean} Window has been initialized
2304 OO.ui.Window.prototype.isInitialized = function () {
2305 return !!this.manager;
2309 * Check if the window is visible.
2311 * @return {boolean} Window is visible
2313 OO.ui.Window.prototype.isVisible = function () {
2314 return this.visible;
2318 * Check if the window is opening.
2320 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
2323 * @return {boolean} Window is opening
2325 OO.ui.Window.prototype.isOpening = function () {
2326 return this.manager.isOpening( this );
2330 * Check if the window is closing.
2332 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
2334 * @return {boolean} Window is closing
2336 OO.ui.Window.prototype.isClosing = function () {
2337 return this.manager.isClosing( this );
2341 * Check if the window is opened.
2343 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
2345 * @return {boolean} Window is opened
2347 OO.ui.Window.prototype.isOpened = function () {
2348 return this.manager.isOpened( this );
2352 * Get the window manager.
2354 * All windows must be attached to a window manager, which is used to open
2355 * and close the window and control its presentation.
2357 * @return {OO.ui.WindowManager} Manager of window
2359 OO.ui.Window.prototype.getManager = function () {
2360 return this.manager;
2364 * Get the symbolic name of the window size (e.g., `small` or `medium`).
2366 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
2368 OO.ui.Window.prototype.getSize = function () {
2369 var viewport = OO.ui.Element.static.getDimensions( this.getElementWindow() ),
2370 sizes = this.manager.constructor.static.sizes,
2373 if ( !sizes[ size ] ) {
2374 size = this.manager.constructor.static.defaultSize;
2376 if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) {
2384 * Get the size properties associated with the current window size
2386 * @return {Object} Size properties
2388 OO.ui.Window.prototype.getSizeProperties = function () {
2389 return this.manager.constructor.static.sizes[ this.getSize() ];
2393 * Disable transitions on window's frame for the duration of the callback function, then enable them
2397 * @param {Function} callback Function to call while transitions are disabled
2399 OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) {
2400 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2401 // Disable transitions first, otherwise we'll get values from when the window was animating.
2403 styleObj = this.$frame[ 0 ].style;
2404 oldTransition = styleObj.transition || styleObj.OTransition || styleObj.MsTransition ||
2405 styleObj.MozTransition || styleObj.WebkitTransition;
2406 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
2407 styleObj.MozTransition = styleObj.WebkitTransition = 'none';
2409 // Force reflow to make sure the style changes done inside callback really are not transitioned
2410 this.$frame.height();
2411 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
2412 styleObj.MozTransition = styleObj.WebkitTransition = oldTransition;
2416 * Get the height of the full window contents (i.e., the window head, body and foot together).
2418 * What consistitutes the head, body, and foot varies depending on the window type.
2419 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
2420 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
2421 * and special actions in the head, and dialog content in the body.
2423 * To get just the height of the dialog body, use the #getBodyHeight method.
2425 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
2427 OO.ui.Window.prototype.getContentHeight = function () {
2430 bodyStyleObj = this.$body[ 0 ].style,
2431 frameStyleObj = this.$frame[ 0 ].style;
2433 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2434 // Disable transitions first, otherwise we'll get values from when the window was animating.
2435 this.withoutSizeTransitions( function () {
2436 var oldHeight = frameStyleObj.height,
2437 oldPosition = bodyStyleObj.position;
2438 frameStyleObj.height = '1px';
2439 // Force body to resize to new width
2440 bodyStyleObj.position = 'relative';
2441 bodyHeight = win.getBodyHeight();
2442 frameStyleObj.height = oldHeight;
2443 bodyStyleObj.position = oldPosition;
2447 // Add buffer for border
2448 ( this.$frame.outerHeight() - this.$frame.innerHeight() ) +
2449 // Use combined heights of children
2450 ( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) )
2455 * Get the height of the window body.
2457 * To get the height of the full window contents (the window body, head, and foot together),
2458 * use #getContentHeight.
2460 * When this function is called, the window will temporarily have been resized
2461 * to height=1px, so .scrollHeight measurements can be taken accurately.
2463 * @return {number} Height of the window body in pixels
2465 OO.ui.Window.prototype.getBodyHeight = function () {
2466 return this.$body[ 0 ].scrollHeight;
2470 * Get the directionality of the frame (right-to-left or left-to-right).
2472 * @return {string} Directionality: `'ltr'` or `'rtl'`
2474 OO.ui.Window.prototype.getDir = function () {
2475 return OO.ui.Element.static.getDir( this.$content ) || 'ltr';
2479 * Get the 'setup' process.
2481 * The setup process is used to set up a window for use in a particular context,
2482 * based on the `data` argument. This method is called during the opening phase of the window’s
2485 * Override this method to add additional steps to the ‘setup’ process the parent method provides
2486 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2489 * To add window content that persists between openings, you may wish to use the #initialize method
2492 * @param {Object} [data] Window opening data
2493 * @return {OO.ui.Process} Setup process
2495 OO.ui.Window.prototype.getSetupProcess = function () {
2496 return new OO.ui.Process();
2500 * Get the ‘ready’ process.
2502 * The ready process is used to ready a window for use in a particular
2503 * context, based on the `data` argument. This method is called during the opening phase of
2504 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2506 * Override this method to add additional steps to the ‘ready’ process the parent method
2507 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2508 * methods of OO.ui.Process.
2510 * @param {Object} [data] Window opening data
2511 * @return {OO.ui.Process} Ready process
2513 OO.ui.Window.prototype.getReadyProcess = function () {
2514 return new OO.ui.Process();
2518 * Get the 'hold' process.
2520 * The hold proccess is used to keep a window from being used in a particular context,
2521 * based on the `data` argument. This method is called during the closing phase of the window’s
2524 * Override this method to add additional steps to the 'hold' process the parent method provides
2525 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2528 * @param {Object} [data] Window closing data
2529 * @return {OO.ui.Process} Hold process
2531 OO.ui.Window.prototype.getHoldProcess = function () {
2532 return new OO.ui.Process();
2536 * Get the ‘teardown’ process.
2538 * The teardown process is used to teardown a window after use. During teardown,
2539 * user interactions within the window are conveyed and the window is closed, based on the `data`
2540 * argument. This method is called during the closing phase of the window’s lifecycle.
2542 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2543 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2546 * @param {Object} [data] Window closing data
2547 * @return {OO.ui.Process} Teardown process
2549 OO.ui.Window.prototype.getTeardownProcess = function () {
2550 return new OO.ui.Process();
2554 * Set the window manager.
2556 * This will cause the window to initialize. Calling it more than once will cause an error.
2558 * @param {OO.ui.WindowManager} manager Manager for this window
2559 * @throws {Error} An error is thrown if the method is called more than once
2562 OO.ui.Window.prototype.setManager = function ( manager ) {
2563 if ( this.manager ) {
2564 throw new Error( 'Cannot set window manager, window already has a manager' );
2567 this.manager = manager;
2574 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2576 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2580 OO.ui.Window.prototype.setSize = function ( size ) {
2587 * Update the window size.
2589 * @throws {Error} An error is thrown if the window is not attached to a window manager
2592 OO.ui.Window.prototype.updateSize = function () {
2593 if ( !this.manager ) {
2594 throw new Error( 'Cannot update window size, must be attached to a manager' );
2597 this.manager.updateWindowSize( this );
2603 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2604 * when the window is opening. In general, setDimensions should not be called directly.
2606 * To set the size of the window, use the #setSize method.
2608 * @param {Object} dim CSS dimension properties
2609 * @param {string|number} [dim.width] Width
2610 * @param {string|number} [dim.minWidth] Minimum width
2611 * @param {string|number} [dim.maxWidth] Maximum width
2612 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2613 * @param {string|number} [dim.minWidth] Minimum height
2614 * @param {string|number} [dim.maxWidth] Maximum height
2617 OO.ui.Window.prototype.setDimensions = function ( dim ) {
2620 styleObj = this.$frame[ 0 ].style;
2622 // Calculate the height we need to set using the correct width
2623 if ( dim.height === undefined ) {
2624 this.withoutSizeTransitions( function () {
2625 var oldWidth = styleObj.width;
2626 win.$frame.css( 'width', dim.width || '' );
2627 height = win.getContentHeight();
2628 styleObj.width = oldWidth;
2631 height = dim.height;
2635 width: dim.width || '',
2636 minWidth: dim.minWidth || '',
2637 maxWidth: dim.maxWidth || '',
2638 height: height || '',
2639 minHeight: dim.minHeight || '',
2640 maxHeight: dim.maxHeight || ''
2647 * Initialize window contents.
2649 * Before the window is opened for the first time, #initialize is called so that content that
2650 * persists between openings can be added to the window.
2652 * To set up a window with new content each time the window opens, use #getSetupProcess.
2654 * @throws {Error} An error is thrown if the window is not attached to a window manager
2657 OO.ui.Window.prototype.initialize = function () {
2658 if ( !this.manager ) {
2659 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2663 this.$head = $( '<div>' );
2664 this.$body = $( '<div>' );
2665 this.$foot = $( '<div>' );
2666 this.$document = $( this.getElementDocument() );
2669 this.$element.on( 'mousedown', this.onMouseDown.bind( this ) );
2672 this.$head.addClass( 'oo-ui-window-head' );
2673 this.$body.addClass( 'oo-ui-window-body' );
2674 this.$foot.addClass( 'oo-ui-window-foot' );
2675 this.$content.append( this.$head, this.$body, this.$foot );
2681 * Called when someone tries to focus the hidden element at the end of the dialog.
2682 * Sends focus back to the start of the dialog.
2684 * @param {jQuery.Event} event Focus event
2686 OO.ui.Window.prototype.onFocusTrapFocused = function ( event ) {
2687 if ( this.$focusTrapBefore.is( event.target ) ) {
2688 OO.ui.findFocusable( this.$content, true ).focus();
2690 // this.$content is the part of the focus cycle, and is the first focusable element
2691 this.$content.focus();
2698 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2699 * method, which returns a promise resolved when the window is done opening.
2701 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2703 * @param {Object} [data] Window opening data
2704 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2705 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2706 * value is a new promise, which is resolved when the window begins closing.
2707 * @throws {Error} An error is thrown if the window is not attached to a window manager
2709 OO.ui.Window.prototype.open = function ( data ) {
2710 if ( !this.manager ) {
2711 throw new Error( 'Cannot open window, must be attached to a manager' );
2714 return this.manager.openWindow( this, data );
2720 * This method is a wrapper around a call to the window
2721 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2722 * which returns a closing promise resolved when the window is done closing.
2724 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2725 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2726 * the window closes.
2728 * @param {Object} [data] Window closing data
2729 * @return {jQuery.Promise} Promise resolved when window is closed
2730 * @throws {Error} An error is thrown if the window is not attached to a window manager
2732 OO.ui.Window.prototype.close = function ( data ) {
2733 if ( !this.manager ) {
2734 throw new Error( 'Cannot close window, must be attached to a manager' );
2737 return this.manager.closeWindow( this, data );
2743 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2746 * @param {Object} [data] Window opening data
2747 * @return {jQuery.Promise} Promise resolved when window is setup
2749 OO.ui.Window.prototype.setup = function ( data ) {
2752 this.toggle( true );
2754 this.focusTrapHandler = OO.ui.bind( this.onFocusTrapFocused, this );
2755 this.$focusTraps.on( 'focus', this.focusTrapHandler );
2757 return this.getSetupProcess( data ).execute().then( function () {
2758 // Force redraw by asking the browser to measure the elements' widths
2759 win.$element.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2760 win.$content.addClass( 'oo-ui-window-content-setup' ).width();
2767 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2770 * @param {Object} [data] Window opening data
2771 * @return {jQuery.Promise} Promise resolved when window is ready
2773 OO.ui.Window.prototype.ready = function ( data ) {
2776 this.$content.focus();
2777 return this.getReadyProcess( data ).execute().then( function () {
2778 // Force redraw by asking the browser to measure the elements' widths
2779 win.$element.addClass( 'oo-ui-window-ready' ).width();
2780 win.$content.addClass( 'oo-ui-window-content-ready' ).width();
2787 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2790 * @param {Object} [data] Window closing data
2791 * @return {jQuery.Promise} Promise resolved when window is held
2793 OO.ui.Window.prototype.hold = function ( data ) {
2796 return this.getHoldProcess( data ).execute().then( function () {
2797 // Get the focused element within the window's content
2798 var $focus = win.$content.find( OO.ui.Element.static.getDocument( win.$content ).activeElement );
2800 // Blur the focused element
2801 if ( $focus.length ) {
2805 // Force redraw by asking the browser to measure the elements' widths
2806 win.$element.removeClass( 'oo-ui-window-ready' ).width();
2807 win.$content.removeClass( 'oo-ui-window-content-ready' ).width();
2814 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2817 * @param {Object} [data] Window closing data
2818 * @return {jQuery.Promise} Promise resolved when window is torn down
2820 OO.ui.Window.prototype.teardown = function ( data ) {
2823 return this.getTeardownProcess( data ).execute().then( function () {
2824 // Force redraw by asking the browser to measure the elements' widths
2825 win.$element.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2826 win.$content.removeClass( 'oo-ui-window-content-setup' ).width();
2827 win.$focusTraps.off( 'focus', win.focusTrapHandler );
2828 win.toggle( false );
2833 * The Dialog class serves as the base class for the other types of dialogs.
2834 * Unless extended to include controls, the rendered dialog box is a simple window
2835 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2836 * which opens, closes, and controls the presentation of the window. See the
2837 * [OOjs UI documentation on MediaWiki] [1] for more information.
2840 * // A simple dialog window.
2841 * function MyDialog( config ) {
2842 * MyDialog.parent.call( this, config );
2844 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2845 * MyDialog.prototype.initialize = function () {
2846 * MyDialog.parent.prototype.initialize.call( this );
2847 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2848 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2849 * this.$body.append( this.content.$element );
2851 * MyDialog.prototype.getBodyHeight = function () {
2852 * return this.content.$element.outerHeight( true );
2854 * var myDialog = new MyDialog( {
2857 * // Create and append a window manager, which opens and closes the window.
2858 * var windowManager = new OO.ui.WindowManager();
2859 * $( 'body' ).append( windowManager.$element );
2860 * windowManager.addWindows( [ myDialog ] );
2861 * // Open the window!
2862 * windowManager.openWindow( myDialog );
2864 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2868 * @extends OO.ui.Window
2869 * @mixins OO.ui.mixin.PendingElement
2872 * @param {Object} [config] Configuration options
2874 OO.ui.Dialog = function OoUiDialog( config ) {
2875 // Parent constructor
2876 OO.ui.Dialog.parent.call( this, config );
2878 // Mixin constructors
2879 OO.ui.mixin.PendingElement.call( this );
2882 this.actions = new OO.ui.ActionSet();
2883 this.attachedActions = [];
2884 this.currentAction = null;
2885 this.onDialogKeyDownHandler = this.onDialogKeyDown.bind( this );
2888 this.actions.connect( this, {
2889 click: 'onActionClick',
2890 resize: 'onActionResize',
2891 change: 'onActionsChange'
2896 .addClass( 'oo-ui-dialog' )
2897 .attr( 'role', 'dialog' );
2902 OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
2903 OO.mixinClass( OO.ui.Dialog, OO.ui.mixin.PendingElement );
2905 /* Static Properties */
2908 * Symbolic name of dialog.
2910 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2911 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2913 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2918 * @property {string}
2920 OO.ui.Dialog.static.name = '';
2925 * The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function
2926 * that will produce a Label node or string. The title can also be specified with data passed to the
2927 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2932 * @property {jQuery|string|Function}
2934 OO.ui.Dialog.static.title = '';
2937 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2939 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2940 * value will be overriden.
2942 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2946 * @property {Object[]}
2948 OO.ui.Dialog.static.actions = [];
2951 * Close the dialog when the 'Esc' key is pressed.
2956 * @property {boolean}
2958 OO.ui.Dialog.static.escapable = true;
2963 * Handle frame document key down events.
2966 * @param {jQuery.Event} e Key down event
2968 OO.ui.Dialog.prototype.onDialogKeyDown = function ( e ) {
2969 if ( e.which === OO.ui.Keys.ESCAPE ) {
2972 e.stopPropagation();
2977 * Handle action resized events.
2980 * @param {OO.ui.ActionWidget} action Action that was resized
2982 OO.ui.Dialog.prototype.onActionResize = function () {
2983 // Override in subclass
2987 * Handle action click events.
2990 * @param {OO.ui.ActionWidget} action Action that was clicked
2992 OO.ui.Dialog.prototype.onActionClick = function ( action ) {
2993 if ( !this.isPending() ) {
2994 this.executeAction( action.getAction() );
2999 * Handle actions change event.
3003 OO.ui.Dialog.prototype.onActionsChange = function () {
3004 this.detachActions();
3005 if ( !this.isClosing() ) {
3006 this.attachActions();
3011 * Get the set of actions used by the dialog.
3013 * @return {OO.ui.ActionSet}
3015 OO.ui.Dialog.prototype.getActions = function () {
3016 return this.actions;
3020 * Get a process for taking action.
3022 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
3023 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
3024 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
3026 * @param {string} [action] Symbolic name of action
3027 * @return {OO.ui.Process} Action process
3029 OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
3030 return new OO.ui.Process()
3031 .next( function () {
3033 // An empty action always closes the dialog without data, which should always be
3034 // safe and make no changes
3043 * @param {Object} [data] Dialog opening data
3044 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
3045 * the {@link #static-title static title}
3046 * @param {Object[]} [data.actions] List of configuration options for each
3047 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
3049 OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
3053 return OO.ui.Dialog.parent.prototype.getSetupProcess.call( this, data )
3054 .next( function () {
3055 var config = this.constructor.static,
3056 actions = data.actions !== undefined ? data.actions : config.actions;
3058 this.title.setLabel(
3059 data.title !== undefined ? data.title : this.constructor.static.title
3061 this.actions.add( this.getActionWidgets( actions ) );
3063 if ( this.constructor.static.escapable ) {
3064 this.$element.on( 'keydown', this.onDialogKeyDownHandler );
3072 OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
3074 return OO.ui.Dialog.parent.prototype.getTeardownProcess.call( this, data )
3075 .first( function () {
3076 if ( this.constructor.static.escapable ) {
3077 this.$element.off( 'keydown', this.onDialogKeyDownHandler );
3080 this.actions.clear();
3081 this.currentAction = null;
3088 OO.ui.Dialog.prototype.initialize = function () {
3092 OO.ui.Dialog.parent.prototype.initialize.call( this );
3094 titleId = OO.ui.generateElementId();
3097 this.title = new OO.ui.LabelWidget( {
3102 this.$content.addClass( 'oo-ui-dialog-content' );
3103 this.$element.attr( 'aria-labelledby', titleId );
3104 this.setPendingElement( this.$head );
3108 * Get action widgets from a list of configs
3110 * @param {Object[]} actions Action widget configs
3111 * @return {OO.ui.ActionWidget[]} Action widgets
3113 OO.ui.Dialog.prototype.getActionWidgets = function ( actions ) {
3114 var i, len, widgets = [];
3115 for ( i = 0, len = actions.length; i < len; i++ ) {
3117 new OO.ui.ActionWidget( actions[ i ] )
3124 * Attach action actions.
3128 OO.ui.Dialog.prototype.attachActions = function () {
3129 // Remember the list of potentially attached actions
3130 this.attachedActions = this.actions.get();
3134 * Detach action actions.
3139 OO.ui.Dialog.prototype.detachActions = function () {
3142 // Detach all actions that may have been previously attached
3143 for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
3144 this.attachedActions[ i ].$element.detach();
3146 this.attachedActions = [];
3150 * Execute an action.
3152 * @param {string} action Symbolic name of action to execute
3153 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
3155 OO.ui.Dialog.prototype.executeAction = function ( action ) {
3157 this.currentAction = action;
3158 return this.getActionProcess( action ).execute()
3159 .always( this.popPending.bind( this ) );
3163 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
3164 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
3165 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
3166 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
3167 * pertinent data and reused.
3169 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
3170 * `opened`, and `closing`, which represent the primary stages of the cycle:
3172 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
3173 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
3175 * - an `opening` event is emitted with an `opening` promise
3176 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
3177 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
3178 * window and its result executed
3179 * - a `setup` progress notification is emitted from the `opening` promise
3180 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
3181 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
3182 * window and its result executed
3183 * - a `ready` progress notification is emitted from the `opening` promise
3184 * - the `opening` promise is resolved with an `opened` promise
3186 * **Opened**: the window is now open.
3188 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
3189 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
3190 * to close the window.
3192 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
3193 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
3194 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
3195 * window and its result executed
3196 * - a `hold` progress notification is emitted from the `closing` promise
3197 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
3198 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
3199 * window and its result executed
3200 * - a `teardown` progress notification is emitted from the `closing` promise
3201 * - the `closing` promise is resolved. The window is now closed
3203 * See the [OOjs UI documentation on MediaWiki][1] for more information.
3205 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3208 * @extends OO.ui.Element
3209 * @mixins OO.EventEmitter
3212 * @param {Object} [config] Configuration options
3213 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
3214 * Note that window classes that are instantiated with a factory must have
3215 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
3216 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
3218 OO.ui.WindowManager = function OoUiWindowManager( config ) {
3219 // Configuration initialization
3220 config = config || {};
3222 // Parent constructor
3223 OO.ui.WindowManager.parent.call( this, config );
3225 // Mixin constructors
3226 OO.EventEmitter.call( this );
3229 this.factory = config.factory;
3230 this.modal = config.modal === undefined || !!config.modal;
3232 this.opening = null;
3234 this.closing = null;
3235 this.preparingToOpen = null;
3236 this.preparingToClose = null;
3237 this.currentWindow = null;
3238 this.globalEvents = false;
3239 this.$ariaHidden = null;
3240 this.onWindowResizeTimeout = null;
3241 this.onWindowResizeHandler = this.onWindowResize.bind( this );
3242 this.afterWindowResizeHandler = this.afterWindowResize.bind( this );
3246 .addClass( 'oo-ui-windowManager' )
3247 .toggleClass( 'oo-ui-windowManager-modal', this.modal );
3252 OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
3253 OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
3258 * An 'opening' event is emitted when the window begins to be opened.
3261 * @param {OO.ui.Window} win Window that's being opened
3262 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
3263 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
3264 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
3265 * @param {Object} data Window opening data
3269 * A 'closing' event is emitted when the window begins to be closed.
3272 * @param {OO.ui.Window} win Window that's being closed
3273 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
3274 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
3275 * processes are complete. When the `closing` promise is resolved, the first argument of its value
3276 * is the closing data.
3277 * @param {Object} data Window closing data
3281 * A 'resize' event is emitted when a window is resized.
3284 * @param {OO.ui.Window} win Window that was resized
3287 /* Static Properties */
3290 * Map of the symbolic name of each window size and its CSS properties.
3294 * @property {Object}
3296 OO.ui.WindowManager.static.sizes = {
3310 // These can be non-numeric because they are never used in calculations
3317 * Symbolic name of the default window size.
3319 * The default size is used if the window's requested size is not recognized.
3323 * @property {string}
3325 OO.ui.WindowManager.static.defaultSize = 'medium';
3330 * Handle window resize events.
3333 * @param {jQuery.Event} e Window resize event
3335 OO.ui.WindowManager.prototype.onWindowResize = function () {
3336 clearTimeout( this.onWindowResizeTimeout );
3337 this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
3341 * Handle window resize events.
3344 * @param {jQuery.Event} e Window resize event
3346 OO.ui.WindowManager.prototype.afterWindowResize = function () {
3347 if ( this.currentWindow ) {
3348 this.updateWindowSize( this.currentWindow );
3353 * Check if window is opening.
3355 * @return {boolean} Window is opening
3357 OO.ui.WindowManager.prototype.isOpening = function ( win ) {
3358 return win === this.currentWindow && !!this.opening && this.opening.state() === 'pending';
3362 * Check if window is closing.
3364 * @return {boolean} Window is closing
3366 OO.ui.WindowManager.prototype.isClosing = function ( win ) {
3367 return win === this.currentWindow && !!this.closing && this.closing.state() === 'pending';
3371 * Check if window is opened.
3373 * @return {boolean} Window is opened
3375 OO.ui.WindowManager.prototype.isOpened = function ( win ) {
3376 return win === this.currentWindow && !!this.opened && this.opened.state() === 'pending';
3380 * Check if a window is being managed.
3382 * @param {OO.ui.Window} win Window to check
3383 * @return {boolean} Window is being managed
3385 OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
3388 for ( name in this.windows ) {
3389 if ( this.windows[ name ] === win ) {
3398 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
3400 * @param {OO.ui.Window} win Window being opened
3401 * @param {Object} [data] Window opening data
3402 * @return {number} Milliseconds to wait
3404 OO.ui.WindowManager.prototype.getSetupDelay = function () {
3409 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
3411 * @param {OO.ui.Window} win Window being opened
3412 * @param {Object} [data] Window opening data
3413 * @return {number} Milliseconds to wait
3415 OO.ui.WindowManager.prototype.getReadyDelay = function () {
3420 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
3422 * @param {OO.ui.Window} win Window being closed
3423 * @param {Object} [data] Window closing data
3424 * @return {number} Milliseconds to wait
3426 OO.ui.WindowManager.prototype.getHoldDelay = function () {
3431 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
3432 * executing the ‘teardown’ process.
3434 * @param {OO.ui.Window} win Window being closed
3435 * @param {Object} [data] Window closing data
3436 * @return {number} Milliseconds to wait
3438 OO.ui.WindowManager.prototype.getTeardownDelay = function () {
3439 return this.modal ? 250 : 0;
3443 * Get a window by its symbolic name.
3445 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
3446 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
3447 * for more information about using factories.
3448 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3450 * @param {string} name Symbolic name of the window
3451 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
3452 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
3453 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
3455 OO.ui.WindowManager.prototype.getWindow = function ( name ) {
3456 var deferred = $.Deferred(),
3457 win = this.windows[ name ];
3459 if ( !( win instanceof OO.ui.Window ) ) {
3460 if ( this.factory ) {
3461 if ( !this.factory.lookup( name ) ) {
3462 deferred.reject( new OO.ui.Error(
3463 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
3466 win = this.factory.create( name );
3467 this.addWindows( [ win ] );
3468 deferred.resolve( win );
3471 deferred.reject( new OO.ui.Error(
3472 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
3476 deferred.resolve( win );
3479 return deferred.promise();
3483 * Get current window.
3485 * @return {OO.ui.Window|null} Currently opening/opened/closing window
3487 OO.ui.WindowManager.prototype.getCurrentWindow = function () {
3488 return this.currentWindow;
3494 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
3495 * @param {Object} [data] Window opening data
3496 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3497 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3500 OO.ui.WindowManager.prototype.openWindow = function ( win, data ) {
3502 opening = $.Deferred();
3504 // Argument handling
3505 if ( typeof win === 'string' ) {
3506 return this.getWindow( win ).then( function ( win ) {
3507 return manager.openWindow( win, data );
3512 if ( !this.hasWindow( win ) ) {
3513 opening.reject( new OO.ui.Error(
3514 'Cannot open window: window is not attached to manager'
3516 } else if ( this.preparingToOpen || this.opening || this.opened ) {
3517 opening.reject( new OO.ui.Error(
3518 'Cannot open window: another window is opening or open'
3523 if ( opening.state() !== 'rejected' ) {
3524 // If a window is currently closing, wait for it to complete
3525 this.preparingToOpen = $.when( this.closing );
3526 // Ensure handlers get called after preparingToOpen is set
3527 this.preparingToOpen.done( function () {
3528 if ( manager.modal ) {
3529 manager.toggleGlobalEvents( true );
3530 manager.toggleAriaIsolation( true );
3532 manager.currentWindow = win;
3533 manager.opening = opening;
3534 manager.preparingToOpen = null;
3535 manager.emit( 'opening', win, opening, data );
3536 setTimeout( function () {
3537 win.setup( data ).then( function () {
3538 manager.updateWindowSize( win );
3539 manager.opening.notify( { state: 'setup' } );
3540 setTimeout( function () {
3541 win.ready( data ).then( function () {
3542 manager.opening.notify( { state: 'ready' } );
3543 manager.opening = null;
3544 manager.opened = $.Deferred();
3545 opening.resolve( manager.opened.promise(), data );
3547 manager.opening = null;
3548 manager.opened = $.Deferred();
3550 manager.closeWindow( win );
3552 }, manager.getReadyDelay() );
3554 manager.opening = null;
3555 manager.opened = $.Deferred();
3557 manager.closeWindow( win );
3559 }, manager.getSetupDelay() );
3563 return opening.promise();
3569 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3570 * @param {Object} [data] Window closing data
3571 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3572 * See {@link #event-closing 'closing' event} for more information about closing promises.
3573 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3576 OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
3578 closing = $.Deferred(),
3581 // Argument handling
3582 if ( typeof win === 'string' ) {
3583 win = this.windows[ win ];
3584 } else if ( !this.hasWindow( win ) ) {
3590 closing.reject( new OO.ui.Error(
3591 'Cannot close window: window is not attached to manager'
3593 } else if ( win !== this.currentWindow ) {
3594 closing.reject( new OO.ui.Error(
3595 'Cannot close window: window already closed with different data'
3597 } else if ( this.preparingToClose || this.closing ) {
3598 closing.reject( new OO.ui.Error(
3599 'Cannot close window: window already closing with different data'
3604 if ( closing.state() !== 'rejected' ) {
3605 // If the window is currently opening, close it when it's done
3606 this.preparingToClose = $.when( this.opening );
3607 // Ensure handlers get called after preparingToClose is set
3608 this.preparingToClose.always( function () {
3609 manager.closing = closing;
3610 manager.preparingToClose = null;
3611 manager.emit( 'closing', win, closing, data );
3612 opened = manager.opened;
3613 manager.opened = null;
3614 opened.resolve( closing.promise(), data );
3615 setTimeout( function () {
3616 win.hold( data ).then( function () {
3617 closing.notify( { state: 'hold' } );
3618 setTimeout( function () {
3619 win.teardown( data ).then( function () {
3620 closing.notify( { state: 'teardown' } );
3621 if ( manager.modal ) {
3622 manager.toggleGlobalEvents( false );
3623 manager.toggleAriaIsolation( false );
3625 manager.closing = null;
3626 manager.currentWindow = null;
3627 closing.resolve( data );
3629 }, manager.getTeardownDelay() );
3631 }, manager.getHoldDelay() );
3635 return closing.promise();
3639 * Add windows to the window manager.
3641 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3642 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3643 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3645 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3646 * by reference, symbolic name, or explicitly defined symbolic names.
3647 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3648 * explicit nor a statically configured symbolic name.
3650 OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
3651 var i, len, win, name, list;
3653 if ( Array.isArray( windows ) ) {
3654 // Convert to map of windows by looking up symbolic names from static configuration
3656 for ( i = 0, len = windows.length; i < len; i++ ) {
3657 name = windows[ i ].constructor.static.name;
3658 if ( typeof name !== 'string' ) {
3659 throw new Error( 'Cannot add window' );
3661 list[ name ] = windows[ i ];
3663 } else if ( OO.isPlainObject( windows ) ) {
3668 for ( name in list ) {
3670 this.windows[ name ] = win.toggle( false );
3671 this.$element.append( win.$element );
3672 win.setManager( this );
3677 * Remove the specified windows from the windows manager.
3679 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3680 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3681 * longer listens to events, use the #destroy method.
3683 * @param {string[]} names Symbolic names of windows to remove
3684 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3685 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3687 OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
3688 var i, len, win, name, cleanupWindow,
3691 cleanup = function ( name, win ) {
3692 delete manager.windows[ name ];
3693 win.$element.detach();
3696 for ( i = 0, len = names.length; i < len; i++ ) {
3698 win = this.windows[ name ];
3700 throw new Error( 'Cannot remove window' );
3702 cleanupWindow = cleanup.bind( null, name, win );
3703 promises.push( this.closeWindow( name ).then( cleanupWindow, cleanupWindow ) );
3706 return $.when.apply( $, promises );
3710 * Remove all windows from the window manager.
3712 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3713 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3714 * To remove just a subset of windows, use the #removeWindows method.
3716 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3718 OO.ui.WindowManager.prototype.clearWindows = function () {
3719 return this.removeWindows( Object.keys( this.windows ) );
3723 * Set dialog size. In general, this method should not be called directly.
3725 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3729 OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
3732 // Bypass for non-current, and thus invisible, windows
3733 if ( win !== this.currentWindow ) {
3737 isFullscreen = win.getSize() === 'full';
3739 this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen );
3740 this.$element.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen );
3741 win.setDimensions( win.getSizeProperties() );
3743 this.emit( 'resize', win );
3749 * Bind or unbind global events for scrolling.
3752 * @param {boolean} [on] Bind global events
3755 OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) {
3756 var scrollWidth, bodyMargin,
3757 $body = $( this.getElementDocument().body ),
3758 // We could have multiple window managers open so only modify
3759 // the body css at the bottom of the stack
3760 stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0 ;
3762 on = on === undefined ? !!this.globalEvents : !!on;
3765 if ( !this.globalEvents ) {
3766 $( this.getElementWindow() ).on( {
3767 // Start listening for top-level window dimension changes
3768 'orientationchange resize': this.onWindowResizeHandler
3770 if ( stackDepth === 0 ) {
3771 scrollWidth = window.innerWidth - document.documentElement.clientWidth;
3772 bodyMargin = parseFloat( $body.css( 'margin-right' ) ) || 0;
3775 'margin-right': bodyMargin + scrollWidth
3779 this.globalEvents = true;
3781 } else if ( this.globalEvents ) {
3782 $( this.getElementWindow() ).off( {
3783 // Stop listening for top-level window dimension changes
3784 'orientationchange resize': this.onWindowResizeHandler
3787 if ( stackDepth === 0 ) {
3793 this.globalEvents = false;
3795 $body.data( 'windowManagerGlobalEvents', stackDepth );
3801 * Toggle screen reader visibility of content other than the window manager.
3804 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3807 OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) {
3808 isolate = isolate === undefined ? !this.$ariaHidden : !!isolate;
3811 if ( !this.$ariaHidden ) {
3812 // Hide everything other than the window manager from screen readers
3813 this.$ariaHidden = $( 'body' )
3815 .not( this.$element.parentsUntil( 'body' ).last() )
3816 .attr( 'aria-hidden', '' );
3818 } else if ( this.$ariaHidden ) {
3819 // Restore screen reader visibility
3820 this.$ariaHidden.removeAttr( 'aria-hidden' );
3821 this.$ariaHidden = null;
3828 * Destroy the window manager.
3830 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3831 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3834 OO.ui.WindowManager.prototype.destroy = function () {
3835 this.toggleGlobalEvents( false );
3836 this.toggleAriaIsolation( false );
3837 this.clearWindows();
3838 this.$element.remove();
3842 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3843 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3844 * appearance and functionality of the error interface.
3846 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3847 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3848 * that initiated the failed process will be disabled.
3850 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3853 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3855 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3860 * @param {string|jQuery} message Description of error
3861 * @param {Object} [config] Configuration options
3862 * @cfg {boolean} [recoverable=true] Error is recoverable.
3863 * By default, errors are recoverable, and users can try the process again.
3864 * @cfg {boolean} [warning=false] Error is a warning.
3865 * If the error is a warning, the error interface will include a
3866 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3867 * is not triggered a second time if the user chooses to continue.
3869 OO.ui.Error = function OoUiError( message, config ) {
3870 // Allow passing positional parameters inside the config object
3871 if ( OO.isPlainObject( message ) && config === undefined ) {
3873 message = config.message;
3876 // Configuration initialization
3877 config = config || {};
3880 this.message = message instanceof jQuery ? message : String( message );
3881 this.recoverable = config.recoverable === undefined || !!config.recoverable;
3882 this.warning = !!config.warning;
3887 OO.initClass( OO.ui.Error );
3892 * Check if the error is recoverable.
3894 * If the error is recoverable, users are able to try the process again.
3896 * @return {boolean} Error is recoverable
3898 OO.ui.Error.prototype.isRecoverable = function () {
3899 return this.recoverable;
3903 * Check if the error is a warning.
3905 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3907 * @return {boolean} Error is warning
3909 OO.ui.Error.prototype.isWarning = function () {
3910 return this.warning;
3914 * Get error message as DOM nodes.
3916 * @return {jQuery} Error message in DOM nodes
3918 OO.ui.Error.prototype.getMessage = function () {
3919 return this.message instanceof jQuery ?
3920 this.message.clone() :
3921 $( '<div>' ).text( this.message ).contents();
3925 * Get the error message text.
3927 * @return {string} Error message
3929 OO.ui.Error.prototype.getMessageText = function () {
3930 return this.message instanceof jQuery ? this.message.text() : this.message;
3934 * Wraps an HTML snippet for use with configuration values which default
3935 * to strings. This bypasses the default html-escaping done to string
3941 * @param {string} [content] HTML content
3943 OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
3945 this.content = content;
3950 OO.initClass( OO.ui.HtmlSnippet );
3957 * @return {string} Unchanged HTML snippet.
3959 OO.ui.HtmlSnippet.prototype.toString = function () {
3960 return this.content;
3964 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3967 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3968 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3969 * or stop if the promise is rejected.
3970 * - **function**: the process will execute the function. The process will stop if the function returns
3971 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3972 * will wait for that number of milliseconds before proceeding.
3974 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3975 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3976 * its remaining steps will not be performed.
3981 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3982 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3983 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3984 * a number or promise.
3985 * @return {Object} Step object, with `callback` and `context` properties
3987 OO.ui.Process = function ( step, context ) {
3992 if ( step !== undefined ) {
3993 this.next( step, context );
3999 OO.initClass( OO.ui.Process );
4004 * Start the process.
4006 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
4007 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
4008 * and any remaining steps are not performed.
4010 OO.ui.Process.prototype.execute = function () {
4011 var i, len, promise;
4014 * Continue execution.
4017 * @param {Array} step A function and the context it should be called in
4018 * @return {Function} Function that continues the process
4020 function proceed( step ) {
4021 return function () {
4022 // Execute step in the correct context
4024 result = step.callback.call( step.context );
4026 if ( result === false ) {
4027 // Use rejected promise for boolean false results
4028 return $.Deferred().reject( [] ).promise();
4030 if ( typeof result === 'number' ) {
4032 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
4034 // Use a delayed promise for numbers, expecting them to be in milliseconds
4035 deferred = $.Deferred();
4036 setTimeout( deferred.resolve, result );
4037 return deferred.promise();
4039 if ( result instanceof OO.ui.Error ) {
4040 // Use rejected promise for error
4041 return $.Deferred().reject( [ result ] ).promise();
4043 if ( Array.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) {
4044 // Use rejected promise for list of errors
4045 return $.Deferred().reject( result ).promise();
4047 // Duck-type the object to see if it can produce a promise
4048 if ( result && $.isFunction( result.promise ) ) {
4049 // Use a promise generated from the result
4050 return result.promise();
4052 // Use resolved promise for other results
4053 return $.Deferred().resolve().promise();
4057 if ( this.steps.length ) {
4058 // Generate a chain reaction of promises
4059 promise = proceed( this.steps[ 0 ] )();
4060 for ( i = 1, len = this.steps.length; i < len; i++ ) {
4061 promise = promise.then( proceed( this.steps[ i ] ) );
4064 promise = $.Deferred().resolve().promise();
4071 * Create a process step.
4074 * @param {number|jQuery.Promise|Function} step
4076 * - Number of milliseconds to wait before proceeding
4077 * - Promise that must be resolved before proceeding
4078 * - Function to execute
4079 * - If the function returns a boolean false the process will stop
4080 * - If the function returns a promise, the process will continue to the next
4081 * step when the promise is resolved or stop if the promise is rejected
4082 * - If the function returns a number, the process will wait for that number of
4083 * milliseconds before proceeding
4084 * @param {Object} [context=null] Execution context of the function. The context is
4085 * ignored if the step is a number or promise.
4086 * @return {Object} Step object, with `callback` and `context` properties
4088 OO.ui.Process.prototype.createStep = function ( step, context ) {
4089 if ( typeof step === 'number' || $.isFunction( step.promise ) ) {
4091 callback: function () {
4097 if ( $.isFunction( step ) ) {
4103 throw new Error( 'Cannot create process step: number, promise or function expected' );
4107 * Add step to the beginning of the process.
4109 * @inheritdoc #createStep
4110 * @return {OO.ui.Process} this
4113 OO.ui.Process.prototype.first = function ( step, context ) {
4114 this.steps.unshift( this.createStep( step, context ) );
4119 * Add step to the end of the process.
4121 * @inheritdoc #createStep
4122 * @return {OO.ui.Process} this
4125 OO.ui.Process.prototype.next = function ( step, context ) {
4126 this.steps.push( this.createStep( step, context ) );
4131 * A ToolFactory creates tools on demand. All tools ({@link OO.ui.Tool Tools}, {@link OO.ui.PopupTool PopupTools},
4132 * and {@link OO.ui.ToolGroupTool ToolGroupTools}) must be registered with a tool factory. Tools are
4133 * registered by their symbolic name. See {@link OO.ui.Toolbar toolbars} for an example.
4135 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4137 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4140 * @extends OO.Factory
4143 OO.ui.ToolFactory = function OoUiToolFactory() {
4144 // Parent constructor
4145 OO.ui.ToolFactory.parent.call( this );
4150 OO.inheritClass( OO.ui.ToolFactory, OO.Factory );
4155 * Get tools from the factory
4157 * @param {Array|string} [include] Included tools, see #extract for format
4158 * @param {Array|string} [exclude] Excluded tools, see #extract for format
4159 * @param {Array|string} [promote] Promoted tools, see #extract for format
4160 * @param {Array|string} [demote] Demoted tools, see #extract for format
4161 * @return {string[]} List of tools
4163 OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) {
4164 var i, len, included, promoted, demoted,
4168 // Collect included and not excluded tools
4169 included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) );
4172 promoted = this.extract( promote, used );
4173 demoted = this.extract( demote, used );
4176 for ( i = 0, len = included.length; i < len; i++ ) {
4177 if ( !used[ included[ i ] ] ) {
4178 auto.push( included[ i ] );
4182 return promoted.concat( auto ).concat( demoted );
4186 * Get a flat list of names from a list of names or groups.
4188 * Normally, `collection` is an array of tool specifications. Tools can be specified in the
4191 * - To include an individual tool, use the symbolic name: `{ name: 'tool-name' }` or `'tool-name'`.
4192 * - To include all tools in a group, use the group name: `{ group: 'group-name' }`. (To assign the
4193 * tool to a group, use OO.ui.Tool.static.group.)
4195 * Alternatively, to include all tools that are not yet assigned to any other toolgroup, use the
4196 * catch-all selector `'*'`.
4198 * If `used` is passed, tool names that appear as properties in this object will be considered
4199 * already assigned, and will not be returned even if specified otherwise. The tool names extracted
4200 * by this function call will be added as new properties in the object.
4203 * @param {Array|string} collection List of tools, see above
4204 * @param {Object} [used] Object containing information about used tools, see above
4205 * @return {string[]} List of extracted tool names
4207 OO.ui.ToolFactory.prototype.extract = function ( collection, used ) {
4208 var i, len, item, name, tool,
4211 if ( collection === '*' ) {
4212 for ( name in this.registry ) {
4213 tool = this.registry[ name ];
4215 // Only add tools by group name when auto-add is enabled
4216 tool.static.autoAddToCatchall &&
4217 // Exclude already used tools
4218 ( !used || !used[ name ] )
4222 used[ name ] = true;
4226 } else if ( Array.isArray( collection ) ) {
4227 for ( i = 0, len = collection.length; i < len; i++ ) {
4228 item = collection[ i ];
4229 // Allow plain strings as shorthand for named tools
4230 if ( typeof item === 'string' ) {
4231 item = { name: item };
4233 if ( OO.isPlainObject( item ) ) {
4235 for ( name in this.registry ) {
4236 tool = this.registry[ name ];
4238 // Include tools with matching group
4239 tool.static.group === item.group &&
4240 // Only add tools by group name when auto-add is enabled
4241 tool.static.autoAddToGroup &&
4242 // Exclude already used tools
4243 ( !used || !used[ name ] )
4247 used[ name ] = true;
4251 // Include tools with matching name and exclude already used tools
4252 } else if ( item.name && ( !used || !used[ item.name ] ) ) {
4253 names.push( item.name );
4255 used[ item.name ] = true;
4265 * ToolGroupFactories create {@link OO.ui.ToolGroup toolgroups} on demand. The toolgroup classes must
4266 * specify a symbolic name and be registered with the factory. The following classes are registered by
4269 * - {@link OO.ui.BarToolGroup BarToolGroups} (‘bar’)
4270 * - {@link OO.ui.MenuToolGroup MenuToolGroups} (‘menu’)
4271 * - {@link OO.ui.ListToolGroup ListToolGroups} (‘list’)
4273 * See {@link OO.ui.Toolbar toolbars} for an example.
4275 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4277 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4279 * @extends OO.Factory
4282 OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() {
4283 var i, l, defaultClasses;
4284 // Parent constructor
4285 OO.Factory.call( this );
4287 defaultClasses = this.constructor.static.getDefaultClasses();
4289 // Register default toolgroups
4290 for ( i = 0, l = defaultClasses.length; i < l; i++ ) {
4291 this.register( defaultClasses[ i ] );
4297 OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory );
4299 /* Static Methods */
4302 * Get a default set of classes to be registered on construction.
4304 * @return {Function[]} Default classes
4306 OO.ui.ToolGroupFactory.static.getDefaultClasses = function () {
4309 OO.ui.ListToolGroup,
4321 * @param {Object} [config] Configuration options
4323 OO.ui.Theme = function OoUiTheme( config ) {
4324 // Configuration initialization
4325 config = config || {};
4330 OO.initClass( OO.ui.Theme );
4335 * Get a list of classes to be applied to a widget.
4337 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
4338 * otherwise state transitions will not work properly.
4340 * @param {OO.ui.Element} element Element for which to get classes
4341 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4343 OO.ui.Theme.prototype.getElementClasses = function () {
4344 return { on: [], off: [] };
4348 * Update CSS classes provided by the theme.
4350 * For elements with theme logic hooks, this should be called any time there's a state change.
4352 * @param {OO.ui.Element} element Element for which to update classes
4353 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4355 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
4356 var $elements = $( [] ),
4357 classes = this.getElementClasses( element );
4359 if ( element.$icon ) {
4360 $elements = $elements.add( element.$icon );
4362 if ( element.$indicator ) {
4363 $elements = $elements.add( element.$indicator );
4367 .removeClass( classes.off.join( ' ' ) )
4368 .addClass( classes.on.join( ' ' ) );
4372 * RequestManager is a mixin that manages the lifecycle of a promise-backed request for a widget, such as
4373 * the {@link OO.ui.mixin.LookupElement}.
4380 OO.ui.mixin.RequestManager = function OoUiMixinRequestManager() {
4381 this.requestCache = {};
4382 this.requestQuery = null;
4383 this.requestRequest = null;
4388 OO.initClass( OO.ui.mixin.RequestManager );
4391 * Get request results for the current query.
4393 * @return {jQuery.Promise} Promise object which will be passed response data as the first argument of
4394 * the done event. If the request was aborted to make way for a subsequent request, this promise
4395 * may not be rejected, depending on what jQuery feels like doing.
4397 OO.ui.mixin.RequestManager.prototype.getRequestData = function () {
4399 value = this.getRequestQuery(),
4400 deferred = $.Deferred(),
4403 this.abortRequest();
4404 if ( Object.prototype.hasOwnProperty.call( this.requestCache, value ) ) {
4405 deferred.resolve( this.requestCache[ value ] );
4407 if ( this.pushPending ) {
4410 this.requestQuery = value;
4411 ourRequest = this.requestRequest = this.getRequest();
4413 .always( function () {
4414 // We need to pop pending even if this is an old request, otherwise
4415 // the widget will remain pending forever.
4416 // TODO: this assumes that an aborted request will fail or succeed soon after
4417 // being aborted, or at least eventually. It would be nice if we could popPending()
4418 // at abort time, but only if we knew that we hadn't already called popPending()
4419 // for that request.
4420 if ( widget.popPending ) {
4421 widget.popPending();
4424 .done( function ( response ) {
4425 // If this is an old request (and aborting it somehow caused it to still succeed),
4426 // ignore its success completely
4427 if ( ourRequest === widget.requestRequest ) {
4428 widget.requestQuery = null;
4429 widget.requestRequest = null;
4430 widget.requestCache[ value ] = widget.getRequestCacheDataFromResponse( response );
4431 deferred.resolve( widget.requestCache[ value ] );
4434 .fail( function () {
4435 // If this is an old request (or a request failing because it's being aborted),
4436 // ignore its failure completely
4437 if ( ourRequest === widget.requestRequest ) {
4438 widget.requestQuery = null;
4439 widget.requestRequest = null;
4444 return deferred.promise();
4448 * Abort the currently pending request, if any.
4452 OO.ui.mixin.RequestManager.prototype.abortRequest = function () {
4453 var oldRequest = this.requestRequest;
4455 // First unset this.requestRequest to the fail handler will notice
4456 // that the request is no longer current
4457 this.requestRequest = null;
4458 this.requestQuery = null;
4464 * Get the query to be made.
4469 * @return {string} query to be used
4471 OO.ui.mixin.RequestManager.prototype.getRequestQuery = null;
4474 * Get a new request object of the current query value.
4479 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
4481 OO.ui.mixin.RequestManager.prototype.getRequest = null;
4484 * Pre-process data returned by the request from #getRequest.
4486 * The return value of this function will be cached, and any further queries for the given value
4487 * will use the cache rather than doing API requests.
4492 * @param {Mixed} response Response from server
4493 * @return {Mixed} Cached result data
4495 OO.ui.mixin.RequestManager.prototype.getRequestCacheDataFromResponse = null;
4498 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
4499 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
4500 * order in which users will navigate through the focusable elements via the "tab" key.
4503 * // TabIndexedElement is mixed into the ButtonWidget class
4504 * // to provide a tabIndex property.
4505 * var button1 = new OO.ui.ButtonWidget( {
4509 * var button2 = new OO.ui.ButtonWidget( {
4513 * var button3 = new OO.ui.ButtonWidget( {
4517 * var button4 = new OO.ui.ButtonWidget( {
4521 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
4527 * @param {Object} [config] Configuration options
4528 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
4529 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
4530 * functionality will be applied to it instead.
4531 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
4532 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
4533 * to remove the element from the tab-navigation flow.
4535 OO.ui.mixin.TabIndexedElement = function OoUiMixinTabIndexedElement( config ) {
4536 // Configuration initialization
4537 config = $.extend( { tabIndex: 0 }, config );
4540 this.$tabIndexed = null;
4541 this.tabIndex = null;
4544 this.connect( this, { disable: 'onTabIndexedElementDisable' } );
4547 this.setTabIndex( config.tabIndex );
4548 this.setTabIndexedElement( config.$tabIndexed || this.$element );
4553 OO.initClass( OO.ui.mixin.TabIndexedElement );
4558 * Set the element that should use the tabindex functionality.
4560 * This method is used to retarget a tabindex mixin so that its functionality applies
4561 * to the specified element. If an element is currently using the functionality, the mixin’s
4562 * effect on that element is removed before the new element is set up.
4564 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
4567 OO.ui.mixin.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
4568 var tabIndex = this.tabIndex;
4569 // Remove attributes from old $tabIndexed
4570 this.setTabIndex( null );
4571 // Force update of new $tabIndexed
4572 this.$tabIndexed = $tabIndexed;
4573 this.tabIndex = tabIndex;
4574 return this.updateTabIndex();
4578 * Set the value of the tabindex.
4580 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
4583 OO.ui.mixin.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
4584 tabIndex = typeof tabIndex === 'number' ? tabIndex : null;
4586 if ( this.tabIndex !== tabIndex ) {
4587 this.tabIndex = tabIndex;
4588 this.updateTabIndex();
4595 * Update the `tabindex` attribute, in case of changes to tab index or
4601 OO.ui.mixin.TabIndexedElement.prototype.updateTabIndex = function () {
4602 if ( this.$tabIndexed ) {
4603 if ( this.tabIndex !== null ) {
4604 // Do not index over disabled elements
4605 this.$tabIndexed.attr( {
4606 tabindex: this.isDisabled() ? -1 : this.tabIndex,
4607 // Support: ChromeVox and NVDA
4608 // These do not seem to inherit aria-disabled from parent elements
4609 'aria-disabled': this.isDisabled().toString()
4612 this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
4619 * Handle disable events.
4622 * @param {boolean} disabled Element is disabled
4624 OO.ui.mixin.TabIndexedElement.prototype.onTabIndexedElementDisable = function () {
4625 this.updateTabIndex();
4629 * Get the value of the tabindex.
4631 * @return {number|null} Tabindex value
4633 OO.ui.mixin.TabIndexedElement.prototype.getTabIndex = function () {
4634 return this.tabIndex;
4638 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
4639 * interface element that can be configured with access keys for accessibility.
4640 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
4642 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
4647 * @param {Object} [config] Configuration options
4648 * @cfg {jQuery} [$button] The button element created by the class.
4649 * If this configuration is omitted, the button element will use a generated `<a>`.
4650 * @cfg {boolean} [framed=true] Render the button with a frame
4652 OO.ui.mixin.ButtonElement = function OoUiMixinButtonElement( config ) {
4653 // Configuration initialization
4654 config = config || {};
4657 this.$button = null;
4659 this.active = false;
4660 this.onMouseUpHandler = this.onMouseUp.bind( this );
4661 this.onMouseDownHandler = this.onMouseDown.bind( this );
4662 this.onKeyDownHandler = this.onKeyDown.bind( this );
4663 this.onKeyUpHandler = this.onKeyUp.bind( this );
4664 this.onClickHandler = this.onClick.bind( this );
4665 this.onKeyPressHandler = this.onKeyPress.bind( this );
4668 this.$element.addClass( 'oo-ui-buttonElement' );
4669 this.toggleFramed( config.framed === undefined || config.framed );
4670 this.setButtonElement( config.$button || $( '<a>' ) );
4675 OO.initClass( OO.ui.mixin.ButtonElement );
4677 /* Static Properties */
4680 * Cancel mouse down events.
4682 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4683 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4684 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4689 * @property {boolean}
4691 OO.ui.mixin.ButtonElement.static.cancelButtonMouseDownEvents = true;
4696 * A 'click' event is emitted when the button element is clicked.
4704 * Set the button element.
4706 * This method is used to retarget a button mixin so that its functionality applies to
4707 * the specified button element instead of the one created by the class. If a button element
4708 * is already set, the method will remove the mixin’s effect on that element.
4710 * @param {jQuery} $button Element to use as button
4712 OO.ui.mixin.ButtonElement.prototype.setButtonElement = function ( $button ) {
4713 if ( this.$button ) {
4715 .removeClass( 'oo-ui-buttonElement-button' )
4716 .removeAttr( 'role accesskey' )
4718 mousedown: this.onMouseDownHandler,
4719 keydown: this.onKeyDownHandler,
4720 click: this.onClickHandler,
4721 keypress: this.onKeyPressHandler
4725 this.$button = $button
4726 .addClass( 'oo-ui-buttonElement-button' )
4727 .attr( { role: 'button' } )
4729 mousedown: this.onMouseDownHandler,
4730 keydown: this.onKeyDownHandler,
4731 click: this.onClickHandler,
4732 keypress: this.onKeyPressHandler
4737 * Handles mouse down events.
4740 * @param {jQuery.Event} e Mouse down event
4742 OO.ui.mixin.ButtonElement.prototype.onMouseDown = function ( e ) {
4743 if ( this.isDisabled() || e.which !== 1 ) {
4746 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4747 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4748 // reliably remove the pressed class
4749 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler );
4750 // Prevent change of focus unless specifically configured otherwise
4751 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
4757 * Handles mouse up events.
4760 * @param {jQuery.Event} e Mouse up event
4762 OO.ui.mixin.ButtonElement.prototype.onMouseUp = function ( e ) {
4763 if ( this.isDisabled() || e.which !== 1 ) {
4766 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4767 // Stop listening for mouseup, since we only needed this once
4768 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler );
4772 * Handles mouse click events.
4775 * @param {jQuery.Event} e Mouse click event
4778 OO.ui.mixin.ButtonElement.prototype.onClick = function ( e ) {
4779 if ( !this.isDisabled() && e.which === 1 ) {
4780 if ( this.emit( 'click' ) ) {
4787 * Handles key down events.
4790 * @param {jQuery.Event} e Key down event
4792 OO.ui.mixin.ButtonElement.prototype.onKeyDown = function ( e ) {
4793 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4796 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4797 // Run the keyup handler no matter where the key is when the button is let go, so we can
4798 // reliably remove the pressed class
4799 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler );
4803 * Handles key up events.
4806 * @param {jQuery.Event} e Key up event
4808 OO.ui.mixin.ButtonElement.prototype.onKeyUp = function ( e ) {
4809 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4812 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4813 // Stop listening for keyup, since we only needed this once
4814 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler );
4818 * Handles key press events.
4821 * @param {jQuery.Event} e Key press event
4824 OO.ui.mixin.ButtonElement.prototype.onKeyPress = function ( e ) {
4825 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
4826 if ( this.emit( 'click' ) ) {
4833 * Check if button has a frame.
4835 * @return {boolean} Button is framed
4837 OO.ui.mixin.ButtonElement.prototype.isFramed = function () {
4842 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4844 * @param {boolean} [framed] Make button framed, omit to toggle
4847 OO.ui.mixin.ButtonElement.prototype.toggleFramed = function ( framed ) {
4848 framed = framed === undefined ? !this.framed : !!framed;
4849 if ( framed !== this.framed ) {
4850 this.framed = framed;
4852 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
4853 .toggleClass( 'oo-ui-buttonElement-framed', framed );
4854 this.updateThemeClasses();
4861 * Set the button's active state.
4863 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4864 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4865 * for other button types.
4867 * @param {boolean} value Make button active
4870 OO.ui.mixin.ButtonElement.prototype.setActive = function ( value ) {
4871 this.active = !!value;
4872 this.$element.toggleClass( 'oo-ui-buttonElement-active', this.active );
4877 * Check if the button is active
4879 * @return {boolean} The button is active
4881 OO.ui.mixin.ButtonElement.prototype.isActive = function () {
4886 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4887 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4888 * items from the group is done through the interface the class provides.
4889 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4891 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4897 * @param {Object} [config] Configuration options
4898 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4899 * is omitted, the group element will use a generated `<div>`.
4901 OO.ui.mixin.GroupElement = function OoUiMixinGroupElement( config ) {
4902 // Configuration initialization
4903 config = config || {};
4908 this.aggregateItemEvents = {};
4911 this.setGroupElement( config.$group || $( '<div>' ) );
4917 * Set the group element.
4919 * If an element is already set, items will be moved to the new element.
4921 * @param {jQuery} $group Element to use as group
4923 OO.ui.mixin.GroupElement.prototype.setGroupElement = function ( $group ) {
4926 this.$group = $group;
4927 for ( i = 0, len = this.items.length; i < len; i++ ) {
4928 this.$group.append( this.items[ i ].$element );
4933 * Check if a group contains no items.
4935 * @return {boolean} Group is empty
4937 OO.ui.mixin.GroupElement.prototype.isEmpty = function () {
4938 return !this.items.length;
4942 * Get all items in the group.
4944 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4945 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4948 * @return {OO.ui.Element[]} An array of items.
4950 OO.ui.mixin.GroupElement.prototype.getItems = function () {
4951 return this.items.slice( 0 );
4955 * Get an item by its data.
4957 * Only the first item with matching data will be returned. To return all matching items,
4958 * use the #getItemsFromData method.
4960 * @param {Object} data Item data to search for
4961 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4963 OO.ui.mixin.GroupElement.prototype.getItemFromData = function ( data ) {
4965 hash = OO.getHash( data );
4967 for ( i = 0, len = this.items.length; i < len; i++ ) {
4968 item = this.items[ i ];
4969 if ( hash === OO.getHash( item.getData() ) ) {
4978 * Get items by their data.
4980 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4982 * @param {Object} data Item data to search for
4983 * @return {OO.ui.Element[]} Items with equivalent data
4985 OO.ui.mixin.GroupElement.prototype.getItemsFromData = function ( data ) {
4987 hash = OO.getHash( data ),
4990 for ( i = 0, len = this.items.length; i < len; i++ ) {
4991 item = this.items[ i ];
4992 if ( hash === OO.getHash( item.getData() ) ) {
5001 * Aggregate the events emitted by the group.
5003 * When events are aggregated, the group will listen to all contained items for the event,
5004 * and then emit the event under a new name. The new event will contain an additional leading
5005 * parameter containing the item that emitted the original event. Other arguments emitted from
5006 * the original event are passed through.
5008 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
5009 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
5010 * A `null` value will remove aggregated events.
5012 * @throws {Error} An error is thrown if aggregation already exists.
5014 OO.ui.mixin.GroupElement.prototype.aggregate = function ( events ) {
5015 var i, len, item, add, remove, itemEvent, groupEvent;
5017 for ( itemEvent in events ) {
5018 groupEvent = events[ itemEvent ];
5020 // Remove existing aggregated event
5021 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
5022 // Don't allow duplicate aggregations
5024 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
5026 // Remove event aggregation from existing items
5027 for ( i = 0, len = this.items.length; i < len; i++ ) {
5028 item = this.items[ i ];
5029 if ( item.connect && item.disconnect ) {
5031 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
5032 item.disconnect( this, remove );
5035 // Prevent future items from aggregating event
5036 delete this.aggregateItemEvents[ itemEvent ];
5039 // Add new aggregate event
5041 // Make future items aggregate event
5042 this.aggregateItemEvents[ itemEvent ] = groupEvent;
5043 // Add event aggregation to existing items
5044 for ( i = 0, len = this.items.length; i < len; i++ ) {
5045 item = this.items[ i ];
5046 if ( item.connect && item.disconnect ) {
5048 add[ itemEvent ] = [ 'emit', groupEvent, item ];
5049 item.connect( this, add );
5057 * Add items to the group.
5059 * Items will be added to the end of the group array unless the optional `index` parameter specifies
5060 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
5062 * @param {OO.ui.Element[]} items An array of items to add to the group
5063 * @param {number} [index] Index of the insertion point
5066 OO.ui.mixin.GroupElement.prototype.addItems = function ( items, index ) {
5067 var i, len, item, event, events, currentIndex,
5070 for ( i = 0, len = items.length; i < len; i++ ) {
5073 // Check if item exists then remove it first, effectively "moving" it
5074 currentIndex = this.items.indexOf( item );
5075 if ( currentIndex >= 0 ) {
5076 this.removeItems( [ item ] );
5077 // Adjust index to compensate for removal
5078 if ( currentIndex < index ) {
5083 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
5085 for ( event in this.aggregateItemEvents ) {
5086 events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ];
5088 item.connect( this, events );
5090 item.setElementGroup( this );
5091 itemElements.push( item.$element.get( 0 ) );
5094 if ( index === undefined || index < 0 || index >= this.items.length ) {
5095 this.$group.append( itemElements );
5096 this.items.push.apply( this.items, items );
5097 } else if ( index === 0 ) {
5098 this.$group.prepend( itemElements );
5099 this.items.unshift.apply( this.items, items );
5101 this.items[ index ].$element.before( itemElements );
5102 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
5109 * Remove the specified items from a group.
5111 * Removed items are detached (not removed) from the DOM so that they may be reused.
5112 * To remove all items from a group, you may wish to use the #clearItems method instead.
5114 * @param {OO.ui.Element[]} items An array of items to remove
5117 OO.ui.mixin.GroupElement.prototype.removeItems = function ( items ) {
5118 var i, len, item, index, remove, itemEvent;
5120 // Remove specific items
5121 for ( i = 0, len = items.length; i < len; i++ ) {
5123 index = this.items.indexOf( item );
5124 if ( index !== -1 ) {
5126 item.connect && item.disconnect &&
5127 !$.isEmptyObject( this.aggregateItemEvents )
5130 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
5131 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
5133 item.disconnect( this, remove );
5135 item.setElementGroup( null );
5136 this.items.splice( index, 1 );
5137 item.$element.detach();
5145 * Clear all items from the group.
5147 * Cleared items are detached from the DOM, not removed, so that they may be reused.
5148 * To remove only a subset of items from a group, use the #removeItems method.
5152 OO.ui.mixin.GroupElement.prototype.clearItems = function () {
5153 var i, len, item, remove, itemEvent;
5156 for ( i = 0, len = this.items.length; i < len; i++ ) {
5157 item = this.items[ i ];
5159 item.connect && item.disconnect &&
5160 !$.isEmptyObject( this.aggregateItemEvents )
5163 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
5164 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
5166 item.disconnect( this, remove );
5168 item.setElementGroup( null );
5169 item.$element.detach();
5177 * DraggableElement is a mixin class used to create elements that can be clicked
5178 * and dragged by a mouse to a new position within a group. This class must be used
5179 * in conjunction with OO.ui.mixin.DraggableGroupElement, which provides a container for
5180 * the draggable elements.
5187 OO.ui.mixin.DraggableElement = function OoUiMixinDraggableElement() {
5191 // Initialize and events
5193 .attr( 'draggable', true )
5194 .addClass( 'oo-ui-draggableElement' )
5196 dragstart: this.onDragStart.bind( this ),
5197 dragover: this.onDragOver.bind( this ),
5198 dragend: this.onDragEnd.bind( this ),
5199 drop: this.onDrop.bind( this )
5203 OO.initClass( OO.ui.mixin.DraggableElement );
5210 * A dragstart event is emitted when the user clicks and begins dragging an item.
5211 * @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse.
5216 * A dragend event is emitted when the user drags an item and releases the mouse,
5217 * thus terminating the drag operation.
5222 * A drop event is emitted when the user drags an item and then releases the mouse button
5223 * over a valid target.
5226 /* Static Properties */
5229 * @inheritdoc OO.ui.mixin.ButtonElement
5231 OO.ui.mixin.DraggableElement.static.cancelButtonMouseDownEvents = false;
5236 * Respond to dragstart event.
5239 * @param {jQuery.Event} event jQuery event
5242 OO.ui.mixin.DraggableElement.prototype.onDragStart = function ( e ) {
5243 var dataTransfer = e.originalEvent.dataTransfer;
5244 // Define drop effect
5245 dataTransfer.dropEffect = 'none';
5246 dataTransfer.effectAllowed = 'move';
5248 // We must set up a dataTransfer data property or Firefox seems to
5249 // ignore the fact the element is draggable.
5251 dataTransfer.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
5253 // The above is only for Firefox. Move on if it fails.
5255 // Add dragging class
5256 this.$element.addClass( 'oo-ui-draggableElement-dragging' );
5258 this.emit( 'dragstart', this );
5263 * Respond to dragend event.
5268 OO.ui.mixin.DraggableElement.prototype.onDragEnd = function () {
5269 this.$element.removeClass( 'oo-ui-draggableElement-dragging' );
5270 this.emit( 'dragend' );
5274 * Handle drop event.
5277 * @param {jQuery.Event} event jQuery event
5280 OO.ui.mixin.DraggableElement.prototype.onDrop = function ( e ) {
5282 this.emit( 'drop', e );
5286 * In order for drag/drop to work, the dragover event must
5287 * return false and stop propogation.
5291 OO.ui.mixin.DraggableElement.prototype.onDragOver = function ( e ) {
5297 * Store it in the DOM so we can access from the widget drag event
5300 * @param {number} Item index
5302 OO.ui.mixin.DraggableElement.prototype.setIndex = function ( index ) {
5303 if ( this.index !== index ) {
5305 this.$element.data( 'index', index );
5313 * @return {number} Item index
5315 OO.ui.mixin.DraggableElement.prototype.getIndex = function () {
5320 * DraggableGroupElement is a mixin class used to create a group element to
5321 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
5322 * The class is used with OO.ui.mixin.DraggableElement.
5326 * @mixins OO.ui.mixin.GroupElement
5329 * @param {Object} [config] Configuration options
5330 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
5331 * should match the layout of the items. Items displayed in a single row
5332 * or in several rows should use horizontal orientation. The vertical orientation should only be
5333 * used when the items are displayed in a single column. Defaults to 'vertical'
5335 OO.ui.mixin.DraggableGroupElement = function OoUiMixinDraggableGroupElement( config ) {
5336 // Configuration initialization
5337 config = config || {};
5339 // Parent constructor
5340 OO.ui.mixin.GroupElement.call( this, config );
5343 this.orientation = config.orientation || 'vertical';
5344 this.dragItem = null;
5345 this.itemDragOver = null;
5347 this.sideInsertion = '';
5351 dragstart: 'itemDragStart',
5352 dragend: 'itemDragEnd',
5355 this.connect( this, {
5356 itemDragStart: 'onItemDragStart',
5357 itemDrop: 'onItemDrop',
5358 itemDragEnd: 'onItemDragEnd'
5361 dragover: this.onDragOver.bind( this ),
5362 dragleave: this.onDragLeave.bind( this )
5366 if ( Array.isArray( config.items ) ) {
5367 this.addItems( config.items );
5369 this.$placeholder = $( '<div>' )
5370 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
5372 .addClass( 'oo-ui-draggableGroupElement' )
5373 .append( this.$status )
5374 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' )
5375 .prepend( this.$placeholder );
5379 OO.mixinClass( OO.ui.mixin.DraggableGroupElement, OO.ui.mixin.GroupElement );
5384 * A 'reorder' event is emitted when the order of items in the group changes.
5387 * @param {OO.ui.mixin.DraggableElement} item Reordered item
5388 * @param {number} [newIndex] New index for the item
5394 * Respond to item drag start event
5397 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5399 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragStart = function ( item ) {
5402 // Map the index of each object
5403 for ( i = 0, len = this.items.length; i < len; i++ ) {
5404 this.items[ i ].setIndex( i );
5407 if ( this.orientation === 'horizontal' ) {
5408 // Set the height of the indicator
5409 this.$placeholder.css( {
5410 height: item.$element.outerHeight(),
5414 // Set the width of the indicator
5415 this.$placeholder.css( {
5417 width: item.$element.outerWidth()
5420 this.setDragItem( item );
5424 * Respond to item drag end event
5428 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragEnd = function () {
5429 this.unsetDragItem();
5434 * Handle drop event and switch the order of the items accordingly
5437 * @param {OO.ui.mixin.DraggableElement} item Dropped item
5440 OO.ui.mixin.DraggableGroupElement.prototype.onItemDrop = function ( item ) {
5441 var toIndex = item.getIndex();
5442 // Check if the dropped item is from the current group
5443 // TODO: Figure out a way to configure a list of legally droppable
5444 // elements even if they are not yet in the list
5445 if ( this.getDragItem() ) {
5446 // If the insertion point is 'after', the insertion index
5447 // is shifted to the right (or to the left in RTL, hence 'after')
5448 if ( this.sideInsertion === 'after' ) {
5451 // Emit change event
5452 this.emit( 'reorder', this.getDragItem(), toIndex );
5454 this.unsetDragItem();
5455 // Return false to prevent propogation
5460 * Handle dragleave event.
5464 OO.ui.mixin.DraggableGroupElement.prototype.onDragLeave = function () {
5465 // This means the item was dragged outside the widget
5468 .addClass( 'oo-ui-element-hidden' );
5472 * Respond to dragover event
5475 * @param {jQuery.Event} event Event details
5477 OO.ui.mixin.DraggableGroupElement.prototype.onDragOver = function ( e ) {
5478 var dragOverObj, $optionWidget, itemOffset, itemMidpoint, itemBoundingRect,
5479 itemSize, cssOutput, dragPosition, itemIndex, itemPosition,
5480 clientX = e.originalEvent.clientX,
5481 clientY = e.originalEvent.clientY;
5483 // Get the OptionWidget item we are dragging over
5484 dragOverObj = this.getElementDocument().elementFromPoint( clientX, clientY );
5485 $optionWidget = $( dragOverObj ).closest( '.oo-ui-draggableElement' );
5486 if ( $optionWidget[ 0 ] ) {
5487 itemOffset = $optionWidget.offset();
5488 itemBoundingRect = $optionWidget[ 0 ].getBoundingClientRect();
5489 itemPosition = $optionWidget.position();
5490 itemIndex = $optionWidget.data( 'index' );
5495 this.isDragging() &&
5496 itemIndex !== this.getDragItem().getIndex()
5498 if ( this.orientation === 'horizontal' ) {
5499 // Calculate where the mouse is relative to the item width
5500 itemSize = itemBoundingRect.width;
5501 itemMidpoint = itemBoundingRect.left + itemSize / 2;
5502 dragPosition = clientX;
5503 // Which side of the item we hover over will dictate
5504 // where the placeholder will appear, on the left or
5507 left: dragPosition < itemMidpoint ? itemPosition.left : itemPosition.left + itemSize,
5508 top: itemPosition.top
5511 // Calculate where the mouse is relative to the item height
5512 itemSize = itemBoundingRect.height;
5513 itemMidpoint = itemBoundingRect.top + itemSize / 2;
5514 dragPosition = clientY;
5515 // Which side of the item we hover over will dictate
5516 // where the placeholder will appear, on the top or
5519 top: dragPosition < itemMidpoint ? itemPosition.top : itemPosition.top + itemSize,
5520 left: itemPosition.left
5523 // Store whether we are before or after an item to rearrange
5524 // For horizontal layout, we need to account for RTL, as this is flipped
5525 if ( this.orientation === 'horizontal' && this.$element.css( 'direction' ) === 'rtl' ) {
5526 this.sideInsertion = dragPosition < itemMidpoint ? 'after' : 'before';
5528 this.sideInsertion = dragPosition < itemMidpoint ? 'before' : 'after';
5530 // Add drop indicator between objects
5533 .removeClass( 'oo-ui-element-hidden' );
5535 // This means the item was dragged outside the widget
5538 .addClass( 'oo-ui-element-hidden' );
5545 * Set a dragged item
5547 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5549 OO.ui.mixin.DraggableGroupElement.prototype.setDragItem = function ( item ) {
5550 this.dragItem = item;
5554 * Unset the current dragged item
5556 OO.ui.mixin.DraggableGroupElement.prototype.unsetDragItem = function () {
5557 this.dragItem = null;
5558 this.itemDragOver = null;
5559 this.$placeholder.addClass( 'oo-ui-element-hidden' );
5560 this.sideInsertion = '';
5564 * Get the item that is currently being dragged.
5566 * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
5568 OO.ui.mixin.DraggableGroupElement.prototype.getDragItem = function () {
5569 return this.dragItem;
5573 * Check if an item in the group is currently being dragged.
5575 * @return {Boolean} Item is being dragged
5577 OO.ui.mixin.DraggableGroupElement.prototype.isDragging = function () {
5578 return this.getDragItem() !== null;
5582 * IconElement is often mixed into other classes to generate an icon.
5583 * Icons are graphics, about the size of normal text. They are used to aid the user
5584 * in locating a control or to convey information in a space-efficient way. See the
5585 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
5586 * included in the library.
5588 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5594 * @param {Object} [config] Configuration options
5595 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
5596 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
5597 * the icon element be set to an existing icon instead of the one generated by this class, set a
5598 * value using a jQuery selection. For example:
5600 * // Use a <div> tag instead of a <span>
5602 * // Use an existing icon element instead of the one generated by the class
5603 * $icon: this.$element
5604 * // Use an icon element from a child widget
5605 * $icon: this.childwidget.$element
5606 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
5607 * symbolic names. A map is used for i18n purposes and contains a `default` icon
5608 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
5609 * by the user's language.
5611 * Example of an i18n map:
5613 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5614 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
5615 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5616 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
5617 * text. The icon title is displayed when users move the mouse over the icon.
5619 OO.ui.mixin.IconElement = function OoUiMixinIconElement( config ) {
5620 // Configuration initialization
5621 config = config || {};
5626 this.iconTitle = null;
5629 this.setIcon( config.icon || this.constructor.static.icon );
5630 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
5631 this.setIconElement( config.$icon || $( '<span>' ) );
5636 OO.initClass( OO.ui.mixin.IconElement );
5638 /* Static Properties */
5641 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
5642 * for i18n purposes and contains a `default` icon name and additional names keyed by
5643 * language code. The `default` name is used when no icon is keyed by the user's language.
5645 * Example of an i18n map:
5647 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5649 * Note: the static property will be overridden if the #icon configuration is used.
5653 * @property {Object|string}
5655 OO.ui.mixin.IconElement.static.icon = null;
5658 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5659 * function that returns title text, or `null` for no title.
5661 * The static property will be overridden if the #iconTitle configuration is used.
5665 * @property {string|Function|null}
5667 OO.ui.mixin.IconElement.static.iconTitle = null;
5672 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5673 * applies to the specified icon element instead of the one created by the class. If an icon
5674 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5675 * and mixin methods will no longer affect the element.
5677 * @param {jQuery} $icon Element to use as icon
5679 OO.ui.mixin.IconElement.prototype.setIconElement = function ( $icon ) {
5682 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
5683 .removeAttr( 'title' );
5687 .addClass( 'oo-ui-iconElement-icon' )
5688 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
5689 if ( this.iconTitle !== null ) {
5690 this.$icon.attr( 'title', this.iconTitle );
5693 this.updateThemeClasses();
5697 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5698 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5701 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5702 * by language code, or `null` to remove the icon.
5705 OO.ui.mixin.IconElement.prototype.setIcon = function ( icon ) {
5706 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
5707 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
5709 if ( this.icon !== icon ) {
5711 if ( this.icon !== null ) {
5712 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
5714 if ( icon !== null ) {
5715 this.$icon.addClass( 'oo-ui-icon-' + icon );
5721 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
5722 this.updateThemeClasses();
5728 * Set the icon title. Use `null` to remove the title.
5730 * @param {string|Function|null} iconTitle A text string used as the icon title,
5731 * a function that returns title text, or `null` for no title.
5734 OO.ui.mixin.IconElement.prototype.setIconTitle = function ( iconTitle ) {
5735 iconTitle = typeof iconTitle === 'function' ||
5736 ( typeof iconTitle === 'string' && iconTitle.length ) ?
5737 OO.ui.resolveMsg( iconTitle ) : null;
5739 if ( this.iconTitle !== iconTitle ) {
5740 this.iconTitle = iconTitle;
5742 if ( this.iconTitle !== null ) {
5743 this.$icon.attr( 'title', iconTitle );
5745 this.$icon.removeAttr( 'title' );
5754 * Get the symbolic name of the icon.
5756 * @return {string} Icon name
5758 OO.ui.mixin.IconElement.prototype.getIcon = function () {
5763 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5765 * @return {string} Icon title text
5767 OO.ui.mixin.IconElement.prototype.getIconTitle = function () {
5768 return this.iconTitle;
5772 * IndicatorElement is often mixed into other classes to generate an indicator.
5773 * Indicators are small graphics that are generally used in two ways:
5775 * - To draw attention to the status of an item. For example, an indicator might be
5776 * used to show that an item in a list has errors that need to be resolved.
5777 * - To clarify the function of a control that acts in an exceptional way (a button
5778 * that opens a menu instead of performing an action directly, for example).
5780 * For a list of indicators included in the library, please see the
5781 * [OOjs UI documentation on MediaWiki] [1].
5783 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5789 * @param {Object} [config] Configuration options
5790 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5791 * configuration is omitted, the indicator element will use a generated `<span>`.
5792 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5793 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5795 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5796 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5797 * or a function that returns title text. The indicator title is displayed when users move
5798 * the mouse over the indicator.
5800 OO.ui.mixin.IndicatorElement = function OoUiMixinIndicatorElement( config ) {
5801 // Configuration initialization
5802 config = config || {};
5805 this.$indicator = null;
5806 this.indicator = null;
5807 this.indicatorTitle = null;
5810 this.setIndicator( config.indicator || this.constructor.static.indicator );
5811 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
5812 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
5817 OO.initClass( OO.ui.mixin.IndicatorElement );
5819 /* Static Properties */
5822 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5823 * The static property will be overridden if the #indicator configuration is used.
5827 * @property {string|null}
5829 OO.ui.mixin.IndicatorElement.static.indicator = null;
5832 * A text string used as the indicator title, a function that returns title text, or `null`
5833 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5837 * @property {string|Function|null}
5839 OO.ui.mixin.IndicatorElement.static.indicatorTitle = null;
5844 * Set the indicator element.
5846 * If an element is already set, it will be cleaned up before setting up the new element.
5848 * @param {jQuery} $indicator Element to use as indicator
5850 OO.ui.mixin.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
5851 if ( this.$indicator ) {
5853 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
5854 .removeAttr( 'title' );
5857 this.$indicator = $indicator
5858 .addClass( 'oo-ui-indicatorElement-indicator' )
5859 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
5860 if ( this.indicatorTitle !== null ) {
5861 this.$indicator.attr( 'title', this.indicatorTitle );
5864 this.updateThemeClasses();
5868 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5870 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5873 OO.ui.mixin.IndicatorElement.prototype.setIndicator = function ( indicator ) {
5874 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
5876 if ( this.indicator !== indicator ) {
5877 if ( this.$indicator ) {
5878 if ( this.indicator !== null ) {
5879 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
5881 if ( indicator !== null ) {
5882 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
5885 this.indicator = indicator;
5888 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
5889 this.updateThemeClasses();
5895 * Set the indicator title.
5897 * The title is displayed when a user moves the mouse over the indicator.
5899 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5900 * `null` for no indicator title
5903 OO.ui.mixin.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
5904 indicatorTitle = typeof indicatorTitle === 'function' ||
5905 ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ?
5906 OO.ui.resolveMsg( indicatorTitle ) : null;
5908 if ( this.indicatorTitle !== indicatorTitle ) {
5909 this.indicatorTitle = indicatorTitle;
5910 if ( this.$indicator ) {
5911 if ( this.indicatorTitle !== null ) {
5912 this.$indicator.attr( 'title', indicatorTitle );
5914 this.$indicator.removeAttr( 'title' );
5923 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5925 * @return {string} Symbolic name of indicator
5927 OO.ui.mixin.IndicatorElement.prototype.getIndicator = function () {
5928 return this.indicator;
5932 * Get the indicator title.
5934 * The title is displayed when a user moves the mouse over the indicator.
5936 * @return {string} Indicator title text
5938 OO.ui.mixin.IndicatorElement.prototype.getIndicatorTitle = function () {
5939 return this.indicatorTitle;
5943 * LabelElement is often mixed into other classes to generate a label, which
5944 * helps identify the function of an interface element.
5945 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5947 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5953 * @param {Object} [config] Configuration options
5954 * @cfg {jQuery} [$label] The label element created by the class. If this
5955 * configuration is omitted, the label element will use a generated `<span>`.
5956 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
5957 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
5958 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
5959 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5960 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5961 * The label will be truncated to fit if necessary.
5963 OO.ui.mixin.LabelElement = function OoUiMixinLabelElement( config ) {
5964 // Configuration initialization
5965 config = config || {};
5970 this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;
5973 this.setLabel( config.label || this.constructor.static.label );
5974 this.setLabelElement( config.$label || $( '<span>' ) );
5979 OO.initClass( OO.ui.mixin.LabelElement );
5984 * @event labelChange
5985 * @param {string} value
5988 /* Static Properties */
5991 * The label text. The label can be specified as a plaintext string, a function that will
5992 * produce a string in the future, or `null` for no label. The static value will
5993 * be overridden if a label is specified with the #label config option.
5997 * @property {string|Function|null}
5999 OO.ui.mixin.LabelElement.static.label = null;
6004 * Set the label element.
6006 * If an element is already set, it will be cleaned up before setting up the new element.
6008 * @param {jQuery} $label Element to use as label
6010 OO.ui.mixin.LabelElement.prototype.setLabelElement = function ( $label ) {
6011 if ( this.$label ) {
6012 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
6015 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
6016 this.setLabelContent( this.label );
6022 * An empty string will result in the label being hidden. A string containing only whitespace will
6023 * be converted to a single ` `.
6025 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
6026 * text; or null for no label
6029 OO.ui.mixin.LabelElement.prototype.setLabel = function ( label ) {
6030 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
6031 label = ( ( typeof label === 'string' && label.length ) || label instanceof jQuery || label instanceof OO.ui.HtmlSnippet ) ? label : null;
6033 this.$element.toggleClass( 'oo-ui-labelElement', !!label );
6035 if ( this.label !== label ) {
6036 if ( this.$label ) {
6037 this.setLabelContent( label );
6040 this.emit( 'labelChange' );
6049 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
6050 * text; or null for no label
6052 OO.ui.mixin.LabelElement.prototype.getLabel = function () {
6061 OO.ui.mixin.LabelElement.prototype.fitLabel = function () {
6062 if ( this.$label && this.$label.autoEllipsis && this.autoFitLabel ) {
6063 this.$label.autoEllipsis( { hasSpan: false, tooltip: true } );
6070 * Set the content of the label.
6072 * Do not call this method until after the label element has been set by #setLabelElement.
6075 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
6076 * text; or null for no label
6078 OO.ui.mixin.LabelElement.prototype.setLabelContent = function ( label ) {
6079 if ( typeof label === 'string' ) {
6080 if ( label.match( /^\s*$/ ) ) {
6081 // Convert whitespace only string to a single non-breaking space
6082 this.$label.html( ' ' );
6084 this.$label.text( label );
6086 } else if ( label instanceof OO.ui.HtmlSnippet ) {
6087 this.$label.html( label.toString() );
6088 } else if ( label instanceof jQuery ) {
6089 this.$label.empty().append( label );
6091 this.$label.empty();
6096 * LookupElement is a mixin that creates a {@link OO.ui.FloatingMenuSelectWidget menu} of suggested values for
6097 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
6098 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
6099 * from the lookup menu, that value becomes the value of the input field.
6101 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
6102 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
6103 * re-enable lookups.
6105 * See the [OOjs UI demos][1] for an example.
6107 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
6113 * @param {Object} [config] Configuration options
6114 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
6115 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
6116 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
6117 * By default, the lookup menu is not generated and displayed until the user begins to type.
6118 * @cfg {boolean} [highlightFirst=true] Whether the first lookup result should be highlighted (so, that the user can
6119 * take it over into the input with simply pressing return) automatically or not.
6121 OO.ui.mixin.LookupElement = function OoUiMixinLookupElement( config ) {
6122 // Configuration initialization
6123 config = $.extend( { highlightFirst: true }, config );
6125 // Mixin constructors
6126 OO.ui.mixin.RequestManager.call( this, config );
6129 this.$overlay = config.$overlay || this.$element;
6130 this.lookupMenu = new OO.ui.FloatingMenuSelectWidget( {
6133 $container: config.$container || this.$element
6136 this.allowSuggestionsWhenEmpty = config.allowSuggestionsWhenEmpty || false;
6138 this.lookupsDisabled = false;
6139 this.lookupInputFocused = false;
6140 this.lookupHighlightFirstItem = config.highlightFirst;
6144 focus: this.onLookupInputFocus.bind( this ),
6145 blur: this.onLookupInputBlur.bind( this ),
6146 mousedown: this.onLookupInputMouseDown.bind( this )
6148 this.connect( this, { change: 'onLookupInputChange' } );
6149 this.lookupMenu.connect( this, {
6150 toggle: 'onLookupMenuToggle',
6151 choose: 'onLookupMenuItemChoose'
6155 this.$element.addClass( 'oo-ui-lookupElement' );
6156 this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' );
6157 this.$overlay.append( this.lookupMenu.$element );
6162 OO.mixinClass( OO.ui.mixin.LookupElement, OO.ui.mixin.RequestManager );
6167 * Handle input focus event.
6170 * @param {jQuery.Event} e Input focus event
6172 OO.ui.mixin.LookupElement.prototype.onLookupInputFocus = function () {
6173 this.lookupInputFocused = true;
6174 this.populateLookupMenu();
6178 * Handle input blur event.
6181 * @param {jQuery.Event} e Input blur event
6183 OO.ui.mixin.LookupElement.prototype.onLookupInputBlur = function () {
6184 this.closeLookupMenu();
6185 this.lookupInputFocused = false;
6189 * Handle input mouse down event.
6192 * @param {jQuery.Event} e Input mouse down event
6194 OO.ui.mixin.LookupElement.prototype.onLookupInputMouseDown = function () {
6195 // Only open the menu if the input was already focused.
6196 // This way we allow the user to open the menu again after closing it with Esc
6197 // by clicking in the input. Opening (and populating) the menu when initially
6198 // clicking into the input is handled by the focus handler.
6199 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
6200 this.populateLookupMenu();
6205 * Handle input change event.
6208 * @param {string} value New input value
6210 OO.ui.mixin.LookupElement.prototype.onLookupInputChange = function () {
6211 if ( this.lookupInputFocused ) {
6212 this.populateLookupMenu();
6217 * Handle the lookup menu being shown/hidden.
6220 * @param {boolean} visible Whether the lookup menu is now visible.
6222 OO.ui.mixin.LookupElement.prototype.onLookupMenuToggle = function ( visible ) {
6224 // When the menu is hidden, abort any active request and clear the menu.
6225 // This has to be done here in addition to closeLookupMenu(), because
6226 // MenuSelectWidget will close itself when the user presses Esc.
6227 this.abortLookupRequest();
6228 this.lookupMenu.clearItems();
6233 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
6236 * @param {OO.ui.MenuOptionWidget} item Selected item
6238 OO.ui.mixin.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) {
6239 this.setValue( item.getData() );
6246 * @return {OO.ui.FloatingMenuSelectWidget}
6248 OO.ui.mixin.LookupElement.prototype.getLookupMenu = function () {
6249 return this.lookupMenu;
6253 * Disable or re-enable lookups.
6255 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
6257 * @param {boolean} disabled Disable lookups
6259 OO.ui.mixin.LookupElement.prototype.setLookupsDisabled = function ( disabled ) {
6260 this.lookupsDisabled = !!disabled;
6264 * Open the menu. If there are no entries in the menu, this does nothing.
6269 OO.ui.mixin.LookupElement.prototype.openLookupMenu = function () {
6270 if ( !this.lookupMenu.isEmpty() ) {
6271 this.lookupMenu.toggle( true );
6277 * Close the menu, empty it, and abort any pending request.
6282 OO.ui.mixin.LookupElement.prototype.closeLookupMenu = function () {
6283 this.lookupMenu.toggle( false );
6284 this.abortLookupRequest();
6285 this.lookupMenu.clearItems();
6290 * Request menu items based on the input's current value, and when they arrive,
6291 * populate the menu with these items and show the menu.
6293 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
6298 OO.ui.mixin.LookupElement.prototype.populateLookupMenu = function () {
6300 value = this.getValue();
6302 if ( this.lookupsDisabled || this.isReadOnly() ) {
6306 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
6307 if ( !this.allowSuggestionsWhenEmpty && value === '' ) {
6308 this.closeLookupMenu();
6309 // Skip population if there is already a request pending for the current value
6310 } else if ( value !== this.lookupQuery ) {
6311 this.getLookupMenuItems()
6312 .done( function ( items ) {
6313 widget.lookupMenu.clearItems();
6314 if ( items.length ) {
6318 widget.initializeLookupMenuSelection();
6320 widget.lookupMenu.toggle( false );
6323 .fail( function () {
6324 widget.lookupMenu.clearItems();
6332 * Highlight the first selectable item in the menu, if configured.
6337 OO.ui.mixin.LookupElement.prototype.initializeLookupMenuSelection = function () {
6338 if ( this.lookupHighlightFirstItem && !this.lookupMenu.getSelectedItem() ) {
6339 this.lookupMenu.highlightItem( this.lookupMenu.getFirstSelectableItem() );
6344 * Get lookup menu items for the current query.
6347 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
6348 * the done event. If the request was aborted to make way for a subsequent request, this promise
6349 * will not be rejected: it will remain pending forever.
6351 OO.ui.mixin.LookupElement.prototype.getLookupMenuItems = function () {
6352 return this.getRequestData().then( function ( data ) {
6353 return this.getLookupMenuOptionsFromData( data );
6358 * Abort the currently pending lookup request, if any.
6362 OO.ui.mixin.LookupElement.prototype.abortLookupRequest = function () {
6363 this.abortRequest();
6367 * Get a new request object of the current lookup query value.
6372 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
6374 OO.ui.mixin.LookupElement.prototype.getLookupRequest = null;
6377 * Pre-process data returned by the request from #getLookupRequest.
6379 * The return value of this function will be cached, and any further queries for the given value
6380 * will use the cache rather than doing API requests.
6385 * @param {Mixed} response Response from server
6386 * @return {Mixed} Cached result data
6388 OO.ui.mixin.LookupElement.prototype.getLookupCacheDataFromResponse = null;
6391 * Get a list of menu option widgets from the (possibly cached) data returned by
6392 * #getLookupCacheDataFromResponse.
6397 * @param {Mixed} data Cached result data, usually an array
6398 * @return {OO.ui.MenuOptionWidget[]} Menu items
6400 OO.ui.mixin.LookupElement.prototype.getLookupMenuOptionsFromData = null;
6403 * Set the read-only state of the widget.
6405 * This will also disable/enable the lookups functionality.
6407 * @param {boolean} readOnly Make input read-only
6410 OO.ui.mixin.LookupElement.prototype.setReadOnly = function ( readOnly ) {
6412 // Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget
6413 OO.ui.TextInputWidget.prototype.setReadOnly.call( this, readOnly );
6415 // During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor
6416 if ( this.isReadOnly() && this.lookupMenu ) {
6417 this.closeLookupMenu();
6424 * @inheritdoc OO.ui.mixin.RequestManager
6426 OO.ui.mixin.LookupElement.prototype.getRequestQuery = function () {
6427 return this.getValue();
6431 * @inheritdoc OO.ui.mixin.RequestManager
6433 OO.ui.mixin.LookupElement.prototype.getRequest = function () {
6434 return this.getLookupRequest();
6438 * @inheritdoc OO.ui.mixin.RequestManager
6440 OO.ui.mixin.LookupElement.prototype.getRequestCacheDataFromResponse = function ( response ) {
6441 return this.getLookupCacheDataFromResponse( response );
6445 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
6446 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
6447 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
6448 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
6454 * @param {Object} [config] Configuration options
6455 * @cfg {Object} [popup] Configuration to pass to popup
6456 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
6458 OO.ui.mixin.PopupElement = function OoUiMixinPopupElement( config ) {
6459 // Configuration initialization
6460 config = config || {};
6463 this.popup = new OO.ui.PopupWidget( $.extend(
6464 { autoClose: true },
6466 { $autoCloseIgnore: this.$element }
6475 * @return {OO.ui.PopupWidget} Popup widget
6477 OO.ui.mixin.PopupElement.prototype.getPopup = function () {
6482 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
6483 * additional functionality to an element created by another class. The class provides
6484 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
6485 * which are used to customize the look and feel of a widget to better describe its
6486 * importance and functionality.
6488 * The library currently contains the following styling flags for general use:
6490 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
6491 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
6492 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
6494 * The flags affect the appearance of the buttons:
6497 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
6498 * var button1 = new OO.ui.ButtonWidget( {
6499 * label: 'Constructive',
6500 * flags: 'constructive'
6502 * var button2 = new OO.ui.ButtonWidget( {
6503 * label: 'Destructive',
6504 * flags: 'destructive'
6506 * var button3 = new OO.ui.ButtonWidget( {
6507 * label: 'Progressive',
6508 * flags: 'progressive'
6510 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
6512 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
6513 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6515 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6521 * @param {Object} [config] Configuration options
6522 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
6523 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
6524 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6525 * @cfg {jQuery} [$flagged] The flagged element. By default,
6526 * the flagged functionality is applied to the element created by the class ($element).
6527 * If a different element is specified, the flagged functionality will be applied to it instead.
6529 OO.ui.mixin.FlaggedElement = function OoUiMixinFlaggedElement( config ) {
6530 // Configuration initialization
6531 config = config || {};
6535 this.$flagged = null;
6538 this.setFlags( config.flags );
6539 this.setFlaggedElement( config.$flagged || this.$element );
6546 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
6547 * parameter contains the name of each modified flag and indicates whether it was
6550 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
6551 * that the flag was added, `false` that the flag was removed.
6557 * Set the flagged element.
6559 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
6560 * If an element is already set, the method will remove the mixin’s effect on that element.
6562 * @param {jQuery} $flagged Element that should be flagged
6564 OO.ui.mixin.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
6565 var classNames = Object.keys( this.flags ).map( function ( flag ) {
6566 return 'oo-ui-flaggedElement-' + flag;
6569 if ( this.$flagged ) {
6570 this.$flagged.removeClass( classNames );
6573 this.$flagged = $flagged.addClass( classNames );
6577 * Check if the specified flag is set.
6579 * @param {string} flag Name of flag
6580 * @return {boolean} The flag is set
6582 OO.ui.mixin.FlaggedElement.prototype.hasFlag = function ( flag ) {
6583 // This may be called before the constructor, thus before this.flags is set
6584 return this.flags && ( flag in this.flags );
6588 * Get the names of all flags set.
6590 * @return {string[]} Flag names
6592 OO.ui.mixin.FlaggedElement.prototype.getFlags = function () {
6593 // This may be called before the constructor, thus before this.flags is set
6594 return Object.keys( this.flags || {} );
6603 OO.ui.mixin.FlaggedElement.prototype.clearFlags = function () {
6604 var flag, className,
6607 classPrefix = 'oo-ui-flaggedElement-';
6609 for ( flag in this.flags ) {
6610 className = classPrefix + flag;
6611 changes[ flag ] = false;
6612 delete this.flags[ flag ];
6613 remove.push( className );
6616 if ( this.$flagged ) {
6617 this.$flagged.removeClass( remove.join( ' ' ) );
6620 this.updateThemeClasses();
6621 this.emit( 'flag', changes );
6627 * Add one or more flags.
6629 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
6630 * or an object keyed by flag name with a boolean value that indicates whether the flag should
6631 * be added (`true`) or removed (`false`).
6635 OO.ui.mixin.FlaggedElement.prototype.setFlags = function ( flags ) {
6636 var i, len, flag, className,
6640 classPrefix = 'oo-ui-flaggedElement-';
6642 if ( typeof flags === 'string' ) {
6643 className = classPrefix + flags;
6645 if ( !this.flags[ flags ] ) {
6646 this.flags[ flags ] = true;
6647 add.push( className );
6649 } else if ( Array.isArray( flags ) ) {
6650 for ( i = 0, len = flags.length; i < len; i++ ) {
6652 className = classPrefix + flag;
6654 if ( !this.flags[ flag ] ) {
6655 changes[ flag ] = true;
6656 this.flags[ flag ] = true;
6657 add.push( className );
6660 } else if ( OO.isPlainObject( flags ) ) {
6661 for ( flag in flags ) {
6662 className = classPrefix + flag;
6663 if ( flags[ flag ] ) {
6665 if ( !this.flags[ flag ] ) {
6666 changes[ flag ] = true;
6667 this.flags[ flag ] = true;
6668 add.push( className );
6672 if ( this.flags[ flag ] ) {
6673 changes[ flag ] = false;
6674 delete this.flags[ flag ];
6675 remove.push( className );
6681 if ( this.$flagged ) {
6683 .addClass( add.join( ' ' ) )
6684 .removeClass( remove.join( ' ' ) );
6687 this.updateThemeClasses();
6688 this.emit( 'flag', changes );
6694 * TitledElement is mixed into other classes to provide a `title` attribute.
6695 * Titles are rendered by the browser and are made visible when the user moves
6696 * the mouse over the element. Titles are not visible on touch devices.
6699 * // TitledElement provides a 'title' attribute to the
6700 * // ButtonWidget class
6701 * var button = new OO.ui.ButtonWidget( {
6702 * label: 'Button with Title',
6703 * title: 'I am a button'
6705 * $( 'body' ).append( button.$element );
6711 * @param {Object} [config] Configuration options
6712 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6713 * If this config is omitted, the title functionality is applied to $element, the
6714 * element created by the class.
6715 * @cfg {string|Function} [title] The title text or a function that returns text. If
6716 * this config is omitted, the value of the {@link #static-title static title} property is used.
6718 OO.ui.mixin.TitledElement = function OoUiMixinTitledElement( config ) {
6719 // Configuration initialization
6720 config = config || {};
6723 this.$titled = null;
6727 this.setTitle( config.title || this.constructor.static.title );
6728 this.setTitledElement( config.$titled || this.$element );
6733 OO.initClass( OO.ui.mixin.TitledElement );
6735 /* Static Properties */
6738 * The title text, a function that returns text, or `null` for no title. The value of the static property
6739 * is overridden if the #title config option is used.
6743 * @property {string|Function|null}
6745 OO.ui.mixin.TitledElement.static.title = null;
6750 * Set the titled element.
6752 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6753 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6755 * @param {jQuery} $titled Element that should use the 'titled' functionality
6757 OO.ui.mixin.TitledElement.prototype.setTitledElement = function ( $titled ) {
6758 if ( this.$titled ) {
6759 this.$titled.removeAttr( 'title' );
6762 this.$titled = $titled;
6764 this.$titled.attr( 'title', this.title );
6771 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6774 OO.ui.mixin.TitledElement.prototype.setTitle = function ( title ) {
6775 title = typeof title === 'function' ? OO.ui.resolveMsg( title ) : title;
6776 title = ( typeof title === 'string' && title.length ) ? title : null;
6778 if ( this.title !== title ) {
6779 if ( this.$titled ) {
6780 if ( title !== null ) {
6781 this.$titled.attr( 'title', title );
6783 this.$titled.removeAttr( 'title' );
6795 * @return {string} Title string
6797 OO.ui.mixin.TitledElement.prototype.getTitle = function () {
6802 * Element that can be automatically clipped to visible boundaries.
6804 * Whenever the element's natural height changes, you have to call
6805 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
6806 * clipping correctly.
6808 * The dimensions of #$clippableContainer will be compared to the boundaries of the
6809 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
6810 * then #$clippable will be given a fixed reduced height and/or width and will be made
6811 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
6812 * but you can build a static footer by setting #$clippableContainer to an element that contains
6813 * #$clippable and the footer.
6819 * @param {Object} [config] Configuration options
6820 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
6821 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
6822 * omit to use #$clippable
6824 OO.ui.mixin.ClippableElement = function OoUiMixinClippableElement( config ) {
6825 // Configuration initialization
6826 config = config || {};
6829 this.$clippable = null;
6830 this.$clippableContainer = null;
6831 this.clipping = false;
6832 this.clippedHorizontally = false;
6833 this.clippedVertically = false;
6834 this.$clippableScrollableContainer = null;
6835 this.$clippableScroller = null;
6836 this.$clippableWindow = null;
6837 this.idealWidth = null;
6838 this.idealHeight = null;
6839 this.onClippableScrollHandler = this.clip.bind( this );
6840 this.onClippableWindowResizeHandler = this.clip.bind( this );
6843 if ( config.$clippableContainer ) {
6844 this.setClippableContainer( config.$clippableContainer );
6846 this.setClippableElement( config.$clippable || this.$element );
6852 * Set clippable element.
6854 * If an element is already set, it will be cleaned up before setting up the new element.
6856 * @param {jQuery} $clippable Element to make clippable
6858 OO.ui.mixin.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
6859 if ( this.$clippable ) {
6860 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
6861 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6862 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6865 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
6870 * Set clippable container.
6872 * This is the container that will be measured when deciding whether to clip. When clipping,
6873 * #$clippable will be resized in order to keep the clippable container fully visible.
6875 * If the clippable container is unset, #$clippable will be used.
6877 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
6879 OO.ui.mixin.ClippableElement.prototype.setClippableContainer = function ( $clippableContainer ) {
6880 this.$clippableContainer = $clippableContainer;
6881 if ( this.$clippable ) {
6889 * Do not turn clipping on until after the element is attached to the DOM and visible.
6891 * @param {boolean} [clipping] Enable clipping, omit to toggle
6894 OO.ui.mixin.ClippableElement.prototype.toggleClipping = function ( clipping ) {
6895 clipping = clipping === undefined ? !this.clipping : !!clipping;
6897 if ( this.clipping !== clipping ) {
6898 this.clipping = clipping;
6900 this.$clippableScrollableContainer = $( this.getClosestScrollableElementContainer() );
6901 // If the clippable container is the root, we have to listen to scroll events and check
6902 // jQuery.scrollTop on the window because of browser inconsistencies
6903 this.$clippableScroller = this.$clippableScrollableContainer.is( 'html, body' ) ?
6904 $( OO.ui.Element.static.getWindow( this.$clippableScrollableContainer ) ) :
6905 this.$clippableScrollableContainer;
6906 this.$clippableScroller.on( 'scroll', this.onClippableScrollHandler );
6907 this.$clippableWindow = $( this.getElementWindow() )
6908 .on( 'resize', this.onClippableWindowResizeHandler );
6909 // Initial clip after visible
6912 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6913 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6915 this.$clippableScrollableContainer = null;
6916 this.$clippableScroller.off( 'scroll', this.onClippableScrollHandler );
6917 this.$clippableScroller = null;
6918 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
6919 this.$clippableWindow = null;
6927 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6929 * @return {boolean} Element will be clipped to the visible area
6931 OO.ui.mixin.ClippableElement.prototype.isClipping = function () {
6932 return this.clipping;
6936 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6938 * @return {boolean} Part of the element is being clipped
6940 OO.ui.mixin.ClippableElement.prototype.isClipped = function () {
6941 return this.clippedHorizontally || this.clippedVertically;
6945 * Check if the right of the element is being clipped by the nearest scrollable container.
6947 * @return {boolean} Part of the element is being clipped
6949 OO.ui.mixin.ClippableElement.prototype.isClippedHorizontally = function () {
6950 return this.clippedHorizontally;
6954 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6956 * @return {boolean} Part of the element is being clipped
6958 OO.ui.mixin.ClippableElement.prototype.isClippedVertically = function () {
6959 return this.clippedVertically;
6963 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6965 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6966 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6968 OO.ui.mixin.ClippableElement.prototype.setIdealSize = function ( width, height ) {
6969 this.idealWidth = width;
6970 this.idealHeight = height;
6972 if ( !this.clipping ) {
6973 // Update dimensions
6974 this.$clippable.css( { width: width, height: height } );
6976 // While clipping, idealWidth and idealHeight are not considered
6980 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6981 * the element's natural height changes.
6983 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6984 * overlapped by, the visible area of the nearest scrollable container.
6988 OO.ui.mixin.ClippableElement.prototype.clip = function () {
6989 var $container, extraHeight, extraWidth, ccOffset,
6990 $scrollableContainer, scOffset, scHeight, scWidth,
6991 ccWidth, scrollerIsWindow, scrollTop, scrollLeft,
6992 desiredWidth, desiredHeight, allotedWidth, allotedHeight,
6993 naturalWidth, naturalHeight, clipWidth, clipHeight,
6994 buffer = 7; // Chosen by fair dice roll
6996 if ( !this.clipping ) {
6997 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
7001 $container = this.$clippableContainer || this.$clippable;
7002 extraHeight = $container.outerHeight() - this.$clippable.outerHeight();
7003 extraWidth = $container.outerWidth() - this.$clippable.outerWidth();
7004 ccOffset = $container.offset();
7005 $scrollableContainer = this.$clippableScrollableContainer.is( 'html, body' ) ?
7006 this.$clippableWindow : this.$clippableScrollableContainer;
7007 scOffset = $scrollableContainer.offset() || { top: 0, left: 0 };
7008 scHeight = $scrollableContainer.innerHeight() - buffer;
7009 scWidth = $scrollableContainer.innerWidth() - buffer;
7010 ccWidth = $container.outerWidth() + buffer;
7011 scrollerIsWindow = this.$clippableScroller[ 0 ] === this.$clippableWindow[ 0 ];
7012 scrollTop = scrollerIsWindow ? this.$clippableScroller.scrollTop() : 0;
7013 scrollLeft = scrollerIsWindow ? this.$clippableScroller.scrollLeft() : 0;
7014 desiredWidth = ccOffset.left < 0 ?
7015 ccWidth + ccOffset.left :
7016 ( scOffset.left + scrollLeft + scWidth ) - ccOffset.left;
7017 desiredHeight = ( scOffset.top + scrollTop + scHeight ) - ccOffset.top;
7018 allotedWidth = desiredWidth - extraWidth;
7019 allotedHeight = desiredHeight - extraHeight;
7020 naturalWidth = this.$clippable.prop( 'scrollWidth' );
7021 naturalHeight = this.$clippable.prop( 'scrollHeight' );
7022 clipWidth = allotedWidth < naturalWidth;
7023 clipHeight = allotedHeight < naturalHeight;
7026 this.$clippable.css( { overflowX: 'scroll', width: Math.max( 0, allotedWidth ) } );
7028 this.$clippable.css( { width: this.idealWidth ? this.idealWidth - extraWidth : '', overflowX: '' } );
7031 this.$clippable.css( { overflowY: 'scroll', height: Math.max( 0, allotedHeight ) } );
7033 this.$clippable.css( { height: this.idealHeight ? this.idealHeight - extraHeight : '', overflowY: '' } );
7036 // If we stopped clipping in at least one of the dimensions
7037 if ( ( this.clippedHorizontally && !clipWidth ) || ( this.clippedVertically && !clipHeight ) ) {
7038 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
7041 this.clippedHorizontally = clipWidth;
7042 this.clippedVertically = clipHeight;
7048 * Element that will stick under a specified container, even when it is inserted elsewhere in the
7049 * document (for example, in a OO.ui.Window's $overlay).
7051 * The elements's position is automatically calculated and maintained when window is resized or the
7052 * page is scrolled. If you reposition the container manually, you have to call #position to make
7053 * sure the element is still placed correctly.
7055 * As positioning is only possible when both the element and the container are attached to the DOM
7056 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
7057 * the #toggle method to display a floating popup, for example.
7063 * @param {Object} [config] Configuration options
7064 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
7065 * @cfg {jQuery} [$floatableContainer] Node to position below
7067 OO.ui.mixin.FloatableElement = function OoUiMixinFloatableElement( config ) {
7068 // Configuration initialization
7069 config = config || {};
7072 this.$floatable = null;
7073 this.$floatableContainer = null;
7074 this.$floatableWindow = null;
7075 this.$floatableClosestScrollable = null;
7076 this.onFloatableScrollHandler = this.position.bind( this );
7077 this.onFloatableWindowResizeHandler = this.position.bind( this );
7080 this.setFloatableContainer( config.$floatableContainer );
7081 this.setFloatableElement( config.$floatable || this.$element );
7087 * Set floatable element.
7089 * If an element is already set, it will be cleaned up before setting up the new element.
7091 * @param {jQuery} $floatable Element to make floatable
7093 OO.ui.mixin.FloatableElement.prototype.setFloatableElement = function ( $floatable ) {
7094 if ( this.$floatable ) {
7095 this.$floatable.removeClass( 'oo-ui-floatableElement-floatable' );
7096 this.$floatable.css( { left: '', top: '' } );
7099 this.$floatable = $floatable.addClass( 'oo-ui-floatableElement-floatable' );
7104 * Set floatable container.
7106 * The element will be always positioned under the specified container.
7108 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
7110 OO.ui.mixin.FloatableElement.prototype.setFloatableContainer = function ( $floatableContainer ) {
7111 this.$floatableContainer = $floatableContainer;
7112 if ( this.$floatable ) {
7118 * Toggle positioning.
7120 * Do not turn positioning on until after the element is attached to the DOM and visible.
7122 * @param {boolean} [positioning] Enable positioning, omit to toggle
7125 OO.ui.mixin.FloatableElement.prototype.togglePositioning = function ( positioning ) {
7126 var closestScrollableOfContainer, closestScrollableOfFloatable;
7128 positioning = positioning === undefined ? !this.positioning : !!positioning;
7130 if ( this.positioning !== positioning ) {
7131 this.positioning = positioning;
7133 closestScrollableOfContainer = OO.ui.Element.static.getClosestScrollableContainer( this.$floatableContainer[ 0 ] );
7134 closestScrollableOfFloatable = OO.ui.Element.static.getClosestScrollableContainer( this.$floatable[ 0 ] );
7135 if ( closestScrollableOfContainer !== closestScrollableOfFloatable ) {
7136 // If the scrollable is the root, we have to listen to scroll events
7137 // on the window because of browser inconsistencies (or do we? someone should verify this)
7138 if ( $( closestScrollableOfContainer ).is( 'html, body' ) ) {
7139 closestScrollableOfContainer = OO.ui.Element.static.getWindow( closestScrollableOfContainer );
7143 if ( positioning ) {
7144 this.$floatableWindow = $( this.getElementWindow() );
7145 this.$floatableWindow.on( 'resize', this.onFloatableWindowResizeHandler );
7147 if ( closestScrollableOfContainer !== closestScrollableOfFloatable ) {
7148 this.$floatableClosestScrollable = $( closestScrollableOfContainer );
7149 this.$floatableClosestScrollable.on( 'scroll', this.onFloatableScrollHandler );
7152 // Initial position after visible
7155 if ( this.$floatableWindow ) {
7156 this.$floatableWindow.off( 'resize', this.onFloatableWindowResizeHandler );
7157 this.$floatableWindow = null;
7160 if ( this.$floatableClosestScrollable ) {
7161 this.$floatableClosestScrollable.off( 'scroll', this.onFloatableScrollHandler );
7162 this.$floatableClosestScrollable = null;
7165 this.$floatable.css( { left: '', top: '' } );
7173 * Position the floatable below its container.
7175 * This should only be done when both of them are attached to the DOM and visible.
7179 OO.ui.mixin.FloatableElement.prototype.position = function () {
7182 if ( !this.positioning ) {
7186 pos = OO.ui.Element.static.getRelativePosition( this.$floatableContainer, this.$floatable.offsetParent() );
7188 // Position under container
7189 pos.top += this.$floatableContainer.height();
7190 this.$floatable.css( pos );
7192 // We updated the position, so re-evaluate the clipping state.
7193 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
7194 // will not notice the need to update itself.)
7195 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
7196 // it not listen to the right events in the right places?
7205 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
7206 * Accesskeys allow an user to go to a specific element by using
7207 * a shortcut combination of a browser specific keys + the key
7211 * // AccessKeyedElement provides an 'accesskey' attribute to the
7212 * // ButtonWidget class
7213 * var button = new OO.ui.ButtonWidget( {
7214 * label: 'Button with Accesskey',
7217 * $( 'body' ).append( button.$element );
7223 * @param {Object} [config] Configuration options
7224 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
7225 * If this config is omitted, the accesskey functionality is applied to $element, the
7226 * element created by the class.
7227 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
7228 * this config is omitted, no accesskey will be added.
7230 OO.ui.mixin.AccessKeyedElement = function OoUiMixinAccessKeyedElement( config ) {
7231 // Configuration initialization
7232 config = config || {};
7235 this.$accessKeyed = null;
7236 this.accessKey = null;
7239 this.setAccessKey( config.accessKey || null );
7240 this.setAccessKeyedElement( config.$accessKeyed || this.$element );
7245 OO.initClass( OO.ui.mixin.AccessKeyedElement );
7247 /* Static Properties */
7250 * The access key, a function that returns a key, or `null` for no accesskey.
7254 * @property {string|Function|null}
7256 OO.ui.mixin.AccessKeyedElement.static.accessKey = null;
7261 * Set the accesskeyed element.
7263 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
7264 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
7266 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
7268 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKeyedElement = function ( $accessKeyed ) {
7269 if ( this.$accessKeyed ) {
7270 this.$accessKeyed.removeAttr( 'accesskey' );
7273 this.$accessKeyed = $accessKeyed;
7274 if ( this.accessKey ) {
7275 this.$accessKeyed.attr( 'accesskey', this.accessKey );
7282 * @param {string|Function|null} accesskey Key, a function that returns a key, or `null` for no accesskey
7285 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKey = function ( accessKey ) {
7286 accessKey = typeof accessKey === 'string' ? OO.ui.resolveMsg( accessKey ) : null;
7288 if ( this.accessKey !== accessKey ) {
7289 if ( this.$accessKeyed ) {
7290 if ( accessKey !== null ) {
7291 this.$accessKeyed.attr( 'accesskey', accessKey );
7293 this.$accessKeyed.removeAttr( 'accesskey' );
7296 this.accessKey = accessKey;
7305 * @return {string} accessKey string
7307 OO.ui.mixin.AccessKeyedElement.prototype.getAccessKey = function () {
7308 return this.accessKey;
7312 * Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute {@link OO.ui.Toolbar toolbars}.
7313 * Each tool is configured with a static name, title, and icon and is customized with the command to carry
7314 * out when the tool is selected. Tools must also be registered with a {@link OO.ui.ToolFactory tool factory},
7315 * which creates the tools on demand.
7317 * Every Tool subclass must implement two methods:
7319 * - {@link #onUpdateState}
7320 * - {@link #onSelect}
7322 * Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup},
7323 * {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which determine how
7324 * the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an example.
7326 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
7327 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7331 * @extends OO.ui.Widget
7332 * @mixins OO.ui.mixin.IconElement
7333 * @mixins OO.ui.mixin.FlaggedElement
7334 * @mixins OO.ui.mixin.TabIndexedElement
7337 * @param {OO.ui.ToolGroup} toolGroup
7338 * @param {Object} [config] Configuration options
7339 * @cfg {string|Function} [title] Title text or a function that returns text. If this config is omitted, the value of
7340 * the {@link #static-title static title} property is used.
7342 * The title is used in different ways depending on the type of toolgroup that contains the tool. The
7343 * 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
7344 * part of a {@link OO.ui.ListToolGroup list} or {@link OO.ui.MenuToolGroup menu} toolgroup.
7346 * For bar toolgroups, a description of the accelerator key is appended to the title if an accelerator key
7347 * is associated with an action by the same name as the tool and accelerator functionality has been added to the application.
7348 * To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method.
7350 OO.ui.Tool = function OoUiTool( toolGroup, config ) {
7351 // Allow passing positional parameters inside the config object
7352 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
7354 toolGroup = config.toolGroup;
7357 // Configuration initialization
7358 config = config || {};
7360 // Parent constructor
7361 OO.ui.Tool.parent.call( this, config );
7364 this.toolGroup = toolGroup;
7365 this.toolbar = this.toolGroup.getToolbar();
7366 this.active = false;
7367 this.$title = $( '<span>' );
7368 this.$accel = $( '<span>' );
7369 this.$link = $( '<a>' );
7372 // Mixin constructors
7373 OO.ui.mixin.IconElement.call( this, config );
7374 OO.ui.mixin.FlaggedElement.call( this, config );
7375 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$link } ) );
7378 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
7381 this.$title.addClass( 'oo-ui-tool-title' );
7383 .addClass( 'oo-ui-tool-accel' )
7385 // This may need to be changed if the key names are ever localized,
7386 // but for now they are essentially written in English
7391 .addClass( 'oo-ui-tool-link' )
7392 .append( this.$icon, this.$title, this.$accel )
7393 .attr( 'role', 'button' );
7395 .data( 'oo-ui-tool', this )
7397 'oo-ui-tool ' + 'oo-ui-tool-name-' +
7398 this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
7400 .toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel )
7401 .append( this.$link );
7402 this.setTitle( config.title || this.constructor.static.title );
7407 OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
7408 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.IconElement );
7409 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.FlaggedElement );
7410 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.TabIndexedElement );
7412 /* Static Properties */
7418 OO.ui.Tool.static.tagName = 'span';
7421 * Symbolic name of tool.
7423 * The symbolic name is used internally to register the tool with a {@link OO.ui.ToolFactory ToolFactory}. It can
7424 * also be used when adding tools to toolgroups.
7429 * @property {string}
7431 OO.ui.Tool.static.name = '';
7434 * Symbolic name of the group.
7436 * The group name is used to associate tools with each other so that they can be selected later by
7437 * a {@link OO.ui.ToolGroup toolgroup}.
7442 * @property {string}
7444 OO.ui.Tool.static.group = '';
7447 * 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.
7452 * @property {string|Function}
7454 OO.ui.Tool.static.title = '';
7457 * Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup.
7458 * Normally only the icon is displayed, or only the label if no icon is given.
7462 * @property {boolean}
7464 OO.ui.Tool.static.displayBothIconAndLabel = false;
7467 * Add tool to catch-all groups automatically.
7469 * A catch-all group, which contains all tools that do not currently belong to a toolgroup,
7470 * can be included in a toolgroup using the wildcard selector, an asterisk (*).
7474 * @property {boolean}
7476 OO.ui.Tool.static.autoAddToCatchall = true;
7479 * Add tool to named groups automatically.
7481 * By default, tools that are configured with a static ‘group’ property are added
7482 * to that group and will be selected when the symbolic name of the group is specified (e.g., when
7483 * toolgroups include tools by group name).
7486 * @property {boolean}
7489 OO.ui.Tool.static.autoAddToGroup = true;
7492 * Check if this tool is compatible with given data.
7494 * This is a stub that can be overriden to provide support for filtering tools based on an
7495 * arbitrary piece of information (e.g., where the cursor is in a document). The implementation
7496 * must also call this method so that the compatibility check can be performed.
7500 * @param {Mixed} data Data to check
7501 * @return {boolean} Tool can be used with data
7503 OO.ui.Tool.static.isCompatibleWith = function () {
7510 * Handle the toolbar state being updated. This method is called when the
7511 * {@link OO.ui.Toolbar#event-updateState 'updateState' event} is emitted on the
7512 * {@link OO.ui.Toolbar Toolbar} that uses this tool, and should set the state of this tool
7513 * depending on application state (usually by calling #setDisabled to enable or disable the tool,
7514 * or #setActive to mark is as currently in-use or not).
7516 * This is an abstract method that must be overridden in a concrete subclass.
7522 OO.ui.Tool.prototype.onUpdateState = null;
7525 * Handle the tool being selected. This method is called when the user triggers this tool,
7526 * usually by clicking on its label/icon.
7528 * This is an abstract method that must be overridden in a concrete subclass.
7534 OO.ui.Tool.prototype.onSelect = null;
7537 * Check if the tool is active.
7539 * Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed
7540 * with the #setActive method. Additional CSS is applied to the tool to reflect the active state.
7542 * @return {boolean} Tool is active
7544 OO.ui.Tool.prototype.isActive = function () {
7549 * Make the tool appear active or inactive.
7551 * This method should be called within #onSelect or #onUpdateState event handlers to make the tool
7552 * appear pressed or not.
7554 * @param {boolean} state Make tool appear active
7556 OO.ui.Tool.prototype.setActive = function ( state ) {
7557 this.active = !!state;
7558 if ( this.active ) {
7559 this.$element.addClass( 'oo-ui-tool-active' );
7561 this.$element.removeClass( 'oo-ui-tool-active' );
7566 * Set the tool #title.
7568 * @param {string|Function} title Title text or a function that returns text
7571 OO.ui.Tool.prototype.setTitle = function ( title ) {
7572 this.title = OO.ui.resolveMsg( title );
7578 * Get the tool #title.
7580 * @return {string} Title text
7582 OO.ui.Tool.prototype.getTitle = function () {
7587 * Get the tool's symbolic name.
7589 * @return {string} Symbolic name of tool
7591 OO.ui.Tool.prototype.getName = function () {
7592 return this.constructor.static.name;
7598 OO.ui.Tool.prototype.updateTitle = function () {
7599 var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
7600 accelTooltips = this.toolGroup.constructor.static.accelTooltips,
7601 accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
7604 this.$title.text( this.title );
7605 this.$accel.text( accel );
7607 if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
7608 tooltipParts.push( this.title );
7610 if ( accelTooltips && typeof accel === 'string' && accel.length ) {
7611 tooltipParts.push( accel );
7613 if ( tooltipParts.length ) {
7614 this.$link.attr( 'title', tooltipParts.join( ' ' ) );
7616 this.$link.removeAttr( 'title' );
7623 * Destroying the tool removes all event handlers and the tool’s DOM elements.
7624 * Call this method whenever you are done using a tool.
7626 OO.ui.Tool.prototype.destroy = function () {
7627 this.toolbar.disconnect( this );
7628 this.$element.remove();
7632 * Toolbars are complex interface components that permit users to easily access a variety
7633 * of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional commands that are
7634 * part of the toolbar, but not configured as tools.
7636 * Individual tools are customized and then registered with a {@link OO.ui.ToolFactory tool factory}, which creates
7637 * the tools on demand. Each tool has a symbolic name (used when registering the tool), a title (e.g., ‘Insert
7638 * image’), and an icon.
7640 * Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be {@link OO.ui.MenuToolGroup menus}
7641 * of tools, {@link OO.ui.ListToolGroup lists} of tools, or a single {@link OO.ui.BarToolGroup bar} of tools.
7642 * The arrangement and order of the toolgroups is customized when the toolbar is set up. Tools can be presented in
7643 * any order, but each can only appear once in the toolbar.
7645 * The toolbar can be synchronized with the state of the external "application", like a text
7646 * editor's editing area, marking tools as active/inactive (e.g. a 'bold' tool would be shown as
7647 * active when the text cursor was inside bolded text) or enabled/disabled (e.g. a table caption
7648 * tool would be disabled while the user is not editing a table). A state change is signalled by
7649 * emitting the {@link #event-updateState 'updateState' event}, which calls Tools'
7650 * {@link OO.ui.Tool#onUpdateState onUpdateState method}.
7652 * The following is an example of a basic toolbar.
7655 * // Example of a toolbar
7656 * // Create the toolbar
7657 * var toolFactory = new OO.ui.ToolFactory();
7658 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7659 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7661 * // We will be placing status text in this element when tools are used
7662 * var $area = $( '<p>' ).text( 'Toolbar example' );
7664 * // Define the tools that we're going to place in our toolbar
7666 * // Create a class inheriting from OO.ui.Tool
7667 * function SearchTool() {
7668 * SearchTool.parent.apply( this, arguments );
7670 * OO.inheritClass( SearchTool, OO.ui.Tool );
7671 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7672 * // of 'icon' and 'title' (displayed icon and text).
7673 * SearchTool.static.name = 'search';
7674 * SearchTool.static.icon = 'search';
7675 * SearchTool.static.title = 'Search...';
7676 * // Defines the action that will happen when this tool is selected (clicked).
7677 * SearchTool.prototype.onSelect = function () {
7678 * $area.text( 'Search tool clicked!' );
7679 * // Never display this tool as "active" (selected).
7680 * this.setActive( false );
7682 * SearchTool.prototype.onUpdateState = function () {};
7683 * // Make this tool available in our toolFactory and thus our toolbar
7684 * toolFactory.register( SearchTool );
7686 * // Register two more tools, nothing interesting here
7687 * function SettingsTool() {
7688 * SettingsTool.parent.apply( this, arguments );
7690 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7691 * SettingsTool.static.name = 'settings';
7692 * SettingsTool.static.icon = 'settings';
7693 * SettingsTool.static.title = 'Change settings';
7694 * SettingsTool.prototype.onSelect = function () {
7695 * $area.text( 'Settings tool clicked!' );
7696 * this.setActive( false );
7698 * SettingsTool.prototype.onUpdateState = function () {};
7699 * toolFactory.register( SettingsTool );
7701 * // Register two more tools, nothing interesting here
7702 * function StuffTool() {
7703 * StuffTool.parent.apply( this, arguments );
7705 * OO.inheritClass( StuffTool, OO.ui.Tool );
7706 * StuffTool.static.name = 'stuff';
7707 * StuffTool.static.icon = 'ellipsis';
7708 * StuffTool.static.title = 'More stuff';
7709 * StuffTool.prototype.onSelect = function () {
7710 * $area.text( 'More stuff tool clicked!' );
7711 * this.setActive( false );
7713 * StuffTool.prototype.onUpdateState = function () {};
7714 * toolFactory.register( StuffTool );
7716 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7717 * // little popup window (a PopupWidget).
7718 * function HelpTool( toolGroup, config ) {
7719 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7724 * this.popup.$body.append( '<p>I am helpful!</p>' );
7726 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7727 * HelpTool.static.name = 'help';
7728 * HelpTool.static.icon = 'help';
7729 * HelpTool.static.title = 'Help';
7730 * toolFactory.register( HelpTool );
7732 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7733 * // used once (but not all defined tools must be used).
7736 * // 'bar' tool groups display tools' icons only, side-by-side.
7738 * include: [ 'search', 'help' ]
7741 * // 'list' tool groups display both the titles and icons, in a dropdown list.
7743 * indicator: 'down',
7745 * include: [ 'settings', 'stuff' ]
7747 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
7748 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here,
7749 * // since it's more complicated to use. (See the next example snippet on this page.)
7752 * // Create some UI around the toolbar and place it in the document
7753 * var frame = new OO.ui.PanelLayout( {
7757 * var contentFrame = new OO.ui.PanelLayout( {
7761 * frame.$element.append(
7763 * contentFrame.$element.append( $area )
7765 * $( 'body' ).append( frame.$element );
7767 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7769 * toolbar.initialize();
7770 * toolbar.emit( 'updateState' );
7772 * The following example extends the previous one to illustrate 'menu' toolgroups and the usage of
7773 * {@link #event-updateState 'updateState' event}.
7776 * // Create the toolbar
7777 * var toolFactory = new OO.ui.ToolFactory();
7778 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7779 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7781 * // We will be placing status text in this element when tools are used
7782 * var $area = $( '<p>' ).text( 'Toolbar example' );
7784 * // Define the tools that we're going to place in our toolbar
7786 * // Create a class inheriting from OO.ui.Tool
7787 * function SearchTool() {
7788 * SearchTool.parent.apply( this, arguments );
7790 * OO.inheritClass( SearchTool, OO.ui.Tool );
7791 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7792 * // of 'icon' and 'title' (displayed icon and text).
7793 * SearchTool.static.name = 'search';
7794 * SearchTool.static.icon = 'search';
7795 * SearchTool.static.title = 'Search...';
7796 * // Defines the action that will happen when this tool is selected (clicked).
7797 * SearchTool.prototype.onSelect = function () {
7798 * $area.text( 'Search tool clicked!' );
7799 * // Never display this tool as "active" (selected).
7800 * this.setActive( false );
7802 * SearchTool.prototype.onUpdateState = function () {};
7803 * // Make this tool available in our toolFactory and thus our toolbar
7804 * toolFactory.register( SearchTool );
7806 * // Register two more tools, nothing interesting here
7807 * function SettingsTool() {
7808 * SettingsTool.parent.apply( this, arguments );
7809 * this.reallyActive = false;
7811 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7812 * SettingsTool.static.name = 'settings';
7813 * SettingsTool.static.icon = 'settings';
7814 * SettingsTool.static.title = 'Change settings';
7815 * SettingsTool.prototype.onSelect = function () {
7816 * $area.text( 'Settings tool clicked!' );
7817 * // Toggle the active state on each click
7818 * this.reallyActive = !this.reallyActive;
7819 * this.setActive( this.reallyActive );
7820 * // To update the menu label
7821 * this.toolbar.emit( 'updateState' );
7823 * SettingsTool.prototype.onUpdateState = function () {};
7824 * toolFactory.register( SettingsTool );
7826 * // Register two more tools, nothing interesting here
7827 * function StuffTool() {
7828 * StuffTool.parent.apply( this, arguments );
7829 * this.reallyActive = false;
7831 * OO.inheritClass( StuffTool, OO.ui.Tool );
7832 * StuffTool.static.name = 'stuff';
7833 * StuffTool.static.icon = 'ellipsis';
7834 * StuffTool.static.title = 'More stuff';
7835 * StuffTool.prototype.onSelect = function () {
7836 * $area.text( 'More stuff tool clicked!' );
7837 * // Toggle the active state on each click
7838 * this.reallyActive = !this.reallyActive;
7839 * this.setActive( this.reallyActive );
7840 * // To update the menu label
7841 * this.toolbar.emit( 'updateState' );
7843 * StuffTool.prototype.onUpdateState = function () {};
7844 * toolFactory.register( StuffTool );
7846 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7847 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
7848 * function HelpTool( toolGroup, config ) {
7849 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7854 * this.popup.$body.append( '<p>I am helpful!</p>' );
7856 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7857 * HelpTool.static.name = 'help';
7858 * HelpTool.static.icon = 'help';
7859 * HelpTool.static.title = 'Help';
7860 * toolFactory.register( HelpTool );
7862 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7863 * // used once (but not all defined tools must be used).
7866 * // 'bar' tool groups display tools' icons only, side-by-side.
7868 * include: [ 'search', 'help' ]
7871 * // 'menu' tool groups display both the titles and icons, in a dropdown menu.
7872 * // Menu label indicates which items are selected.
7874 * indicator: 'down',
7875 * include: [ 'settings', 'stuff' ]
7879 * // Create some UI around the toolbar and place it in the document
7880 * var frame = new OO.ui.PanelLayout( {
7884 * var contentFrame = new OO.ui.PanelLayout( {
7888 * frame.$element.append(
7890 * contentFrame.$element.append( $area )
7892 * $( 'body' ).append( frame.$element );
7894 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7896 * toolbar.initialize();
7897 * toolbar.emit( 'updateState' );
7900 * @extends OO.ui.Element
7901 * @mixins OO.EventEmitter
7902 * @mixins OO.ui.mixin.GroupElement
7905 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
7906 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups
7907 * @param {Object} [config] Configuration options
7908 * @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are included
7909 * in the toolbar, but are not configured as tools. By default, actions are displayed on the right side of
7911 * @cfg {boolean} [shadow] Add a shadow below the toolbar.
7913 OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
7914 // Allow passing positional parameters inside the config object
7915 if ( OO.isPlainObject( toolFactory ) && config === undefined ) {
7916 config = toolFactory;
7917 toolFactory = config.toolFactory;
7918 toolGroupFactory = config.toolGroupFactory;
7921 // Configuration initialization
7922 config = config || {};
7924 // Parent constructor
7925 OO.ui.Toolbar.parent.call( this, config );
7927 // Mixin constructors
7928 OO.EventEmitter.call( this );
7929 OO.ui.mixin.GroupElement.call( this, config );
7932 this.toolFactory = toolFactory;
7933 this.toolGroupFactory = toolGroupFactory;
7936 this.$bar = $( '<div>' );
7937 this.$actions = $( '<div>' );
7938 this.initialized = false;
7939 this.onWindowResizeHandler = this.onWindowResize.bind( this );
7943 .add( this.$bar ).add( this.$group ).add( this.$actions )
7944 .on( 'mousedown keydown', this.onPointerDown.bind( this ) );
7947 this.$group.addClass( 'oo-ui-toolbar-tools' );
7948 if ( config.actions ) {
7949 this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) );
7952 .addClass( 'oo-ui-toolbar-bar' )
7953 .append( this.$group, '<div style="clear:both"></div>' );
7954 if ( config.shadow ) {
7955 this.$bar.append( '<div class="oo-ui-toolbar-shadow"></div>' );
7957 this.$element.addClass( 'oo-ui-toolbar' ).append( this.$bar );
7962 OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
7963 OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
7964 OO.mixinClass( OO.ui.Toolbar, OO.ui.mixin.GroupElement );
7969 * @event updateState
7971 * An 'updateState' event must be emitted on the Toolbar (by calling `toolbar.emit( 'updateState' )`)
7972 * every time the state of the application using the toolbar changes, and an update to the state of
7973 * tools is required.
7975 * @param {Mixed...} data Application-defined parameters
7981 * Get the tool factory.
7983 * @return {OO.ui.ToolFactory} Tool factory
7985 OO.ui.Toolbar.prototype.getToolFactory = function () {
7986 return this.toolFactory;
7990 * Get the toolgroup factory.
7992 * @return {OO.Factory} Toolgroup factory
7994 OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
7995 return this.toolGroupFactory;
7999 * Handles mouse down events.
8002 * @param {jQuery.Event} e Mouse down event
8004 OO.ui.Toolbar.prototype.onPointerDown = function ( e ) {
8005 var $closestWidgetToEvent = $( e.target ).closest( '.oo-ui-widget' ),
8006 $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
8007 if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[ 0 ] === $closestWidgetToToolbar[ 0 ] ) {
8013 * Handle window resize event.
8016 * @param {jQuery.Event} e Window resize event
8018 OO.ui.Toolbar.prototype.onWindowResize = function () {
8019 this.$element.toggleClass(
8020 'oo-ui-toolbar-narrow',
8021 this.$bar.width() <= this.narrowThreshold
8026 * Sets up handles and preloads required information for the toolbar to work.
8027 * This must be called after it is attached to a visible document and before doing anything else.
8029 OO.ui.Toolbar.prototype.initialize = function () {
8030 if ( !this.initialized ) {
8031 this.initialized = true;
8032 this.narrowThreshold = this.$group.width() + this.$actions.width();
8033 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
8034 this.onWindowResize();
8039 * Set up the toolbar.
8041 * The toolbar is set up with a list of toolgroup configurations that specify the type of
8042 * toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or {@link OO.ui.ListToolGroup list})
8043 * to add and which tools to include, exclude, promote, or demote within that toolgroup. Please
8044 * see {@link OO.ui.ToolGroup toolgroups} for more information about including tools in toolgroups.
8046 * @param {Object.<string,Array>} groups List of toolgroup configurations
8047 * @param {Array|string} [groups.include] Tools to include in the toolgroup
8048 * @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup
8049 * @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup
8050 * @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup
8052 OO.ui.Toolbar.prototype.setup = function ( groups ) {
8053 var i, len, type, group,
8055 defaultType = 'bar';
8057 // Cleanup previous groups
8060 // Build out new groups
8061 for ( i = 0, len = groups.length; i < len; i++ ) {
8062 group = groups[ i ];
8063 if ( group.include === '*' ) {
8064 // Apply defaults to catch-all groups
8065 if ( group.type === undefined ) {
8066 group.type = 'list';
8068 if ( group.label === undefined ) {
8069 group.label = OO.ui.msg( 'ooui-toolbar-more' );
8072 // Check type has been registered
8073 type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
8075 this.getToolGroupFactory().create( type, this, group )
8078 this.addItems( items );
8082 * Remove all tools and toolgroups from the toolbar.
8084 OO.ui.Toolbar.prototype.reset = function () {
8089 for ( i = 0, len = this.items.length; i < len; i++ ) {
8090 this.items[ i ].destroy();
8096 * Destroy the toolbar.
8098 * Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. Call
8099 * this method whenever you are done using a toolbar.
8101 OO.ui.Toolbar.prototype.destroy = function () {
8102 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
8104 this.$element.remove();
8108 * Check if the tool is available.
8110 * Available tools are ones that have not yet been added to the toolbar.
8112 * @param {string} name Symbolic name of tool
8113 * @return {boolean} Tool is available
8115 OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
8116 return !this.tools[ name ];
8120 * Prevent tool from being used again.
8122 * @param {OO.ui.Tool} tool Tool to reserve
8124 OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
8125 this.tools[ tool.getName() ] = tool;
8129 * Allow tool to be used again.
8131 * @param {OO.ui.Tool} tool Tool to release
8133 OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
8134 delete this.tools[ tool.getName() ];
8138 * Get accelerator label for tool.
8140 * The OOjs UI library does not contain an accelerator system, but this is the hook for one. To
8141 * use an accelerator system, subclass the toolbar and override this method, which is meant to return a label
8142 * that describes the accelerator keys for the tool passed (by symbolic name) to the method.
8144 * @param {string} name Symbolic name of tool
8145 * @return {string|undefined} Tool accelerator label if available
8147 OO.ui.Toolbar.prototype.getToolAccelerator = function () {
8152 * ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a {@link OO.ui.Toolbar toolbar}.
8153 * The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or {@link OO.ui.MenuToolGroup menu})
8154 * to which a tool belongs determines how the tool is arranged and displayed in the toolbar. Toolgroups
8155 * themselves are created on demand with a {@link OO.ui.ToolGroupFactory toolgroup factory}.
8157 * Toolgroups can contain individual tools, groups of tools, or all available tools, as specified
8158 * using the `include` config option. See OO.ui.ToolFactory#extract on documentation of the format.
8159 * The options `exclude`, `promote`, and `demote` support the same formats.
8161 * See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in general,
8162 * please see the [OOjs UI documentation on MediaWiki][1].
8164 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
8168 * @extends OO.ui.Widget
8169 * @mixins OO.ui.mixin.GroupElement
8172 * @param {OO.ui.Toolbar} toolbar
8173 * @param {Object} [config] Configuration options
8174 * @cfg {Array|string} [include] List of tools to include in the toolgroup, see above.
8175 * @cfg {Array|string} [exclude] List of tools to exclude from the toolgroup, see above.
8176 * @cfg {Array|string} [promote] List of tools to promote to the beginning of the toolgroup, see above.
8177 * @cfg {Array|string} [demote] List of tools to demote to the end of the toolgroup, see above.
8178 * This setting is particularly useful when tools have been added to the toolgroup
8179 * en masse (e.g., via the catch-all selector).
8181 OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
8182 // Allow passing positional parameters inside the config object
8183 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
8185 toolbar = config.toolbar;
8188 // Configuration initialization
8189 config = config || {};
8191 // Parent constructor
8192 OO.ui.ToolGroup.parent.call( this, config );
8194 // Mixin constructors
8195 OO.ui.mixin.GroupElement.call( this, config );
8198 this.toolbar = toolbar;
8200 this.pressed = null;
8201 this.autoDisabled = false;
8202 this.include = config.include || [];
8203 this.exclude = config.exclude || [];
8204 this.promote = config.promote || [];
8205 this.demote = config.demote || [];
8206 this.onCapturedMouseKeyUpHandler = this.onCapturedMouseKeyUp.bind( this );
8210 mousedown: this.onMouseKeyDown.bind( this ),
8211 mouseup: this.onMouseKeyUp.bind( this ),
8212 keydown: this.onMouseKeyDown.bind( this ),
8213 keyup: this.onMouseKeyUp.bind( this ),
8214 focus: this.onMouseOverFocus.bind( this ),
8215 blur: this.onMouseOutBlur.bind( this ),
8216 mouseover: this.onMouseOverFocus.bind( this ),
8217 mouseout: this.onMouseOutBlur.bind( this )
8219 this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } );
8220 this.aggregate( { disable: 'itemDisable' } );
8221 this.connect( this, { itemDisable: 'updateDisabled' } );
8224 this.$group.addClass( 'oo-ui-toolGroup-tools' );
8226 .addClass( 'oo-ui-toolGroup' )
8227 .append( this.$group );
8233 OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
8234 OO.mixinClass( OO.ui.ToolGroup, OO.ui.mixin.GroupElement );
8242 /* Static Properties */
8245 * Show labels in tooltips.
8249 * @property {boolean}
8251 OO.ui.ToolGroup.static.titleTooltips = false;
8254 * Show acceleration labels in tooltips.
8256 * Note: The OOjs UI library does not include an accelerator system, but does contain
8257 * a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and
8258 * override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is
8259 * meant to return a label that describes the accelerator keys for a given tool (e.g., 'Ctrl + M').
8263 * @property {boolean}
8265 OO.ui.ToolGroup.static.accelTooltips = false;
8268 * Automatically disable the toolgroup when all tools are disabled
8272 * @property {boolean}
8274 OO.ui.ToolGroup.static.autoDisable = true;
8281 OO.ui.ToolGroup.prototype.isDisabled = function () {
8282 return this.autoDisabled || OO.ui.ToolGroup.parent.prototype.isDisabled.apply( this, arguments );
8288 OO.ui.ToolGroup.prototype.updateDisabled = function () {
8289 var i, item, allDisabled = true;
8291 if ( this.constructor.static.autoDisable ) {
8292 for ( i = this.items.length - 1; i >= 0; i-- ) {
8293 item = this.items[ i ];
8294 if ( !item.isDisabled() ) {
8295 allDisabled = false;
8299 this.autoDisabled = allDisabled;
8301 OO.ui.ToolGroup.parent.prototype.updateDisabled.apply( this, arguments );
8305 * Handle mouse down and key down events.
8308 * @param {jQuery.Event} e Mouse down or key down event
8310 OO.ui.ToolGroup.prototype.onMouseKeyDown = function ( e ) {
8312 !this.isDisabled() &&
8313 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
8315 this.pressed = this.getTargetTool( e );
8316 if ( this.pressed ) {
8317 this.pressed.setActive( true );
8318 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler );
8319 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler );
8326 * Handle captured mouse up and key up events.
8329 * @param {Event} e Mouse up or key up event
8331 OO.ui.ToolGroup.prototype.onCapturedMouseKeyUp = function ( e ) {
8332 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler );
8333 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler );
8334 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
8335 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
8336 this.onMouseKeyUp( e );
8340 * Handle mouse up and key up events.
8343 * @param {jQuery.Event} e Mouse up or key up event
8345 OO.ui.ToolGroup.prototype.onMouseKeyUp = function ( e ) {
8346 var tool = this.getTargetTool( e );
8349 !this.isDisabled() && this.pressed && this.pressed === tool &&
8350 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
8352 this.pressed.onSelect();
8353 this.pressed = null;
8357 this.pressed = null;
8361 * Handle mouse over and focus events.
8364 * @param {jQuery.Event} e Mouse over or focus event
8366 OO.ui.ToolGroup.prototype.onMouseOverFocus = function ( e ) {
8367 var tool = this.getTargetTool( e );
8369 if ( this.pressed && this.pressed === tool ) {
8370 this.pressed.setActive( true );
8375 * Handle mouse out and blur events.
8378 * @param {jQuery.Event} e Mouse out or blur event
8380 OO.ui.ToolGroup.prototype.onMouseOutBlur = function ( e ) {
8381 var tool = this.getTargetTool( e );
8383 if ( this.pressed && this.pressed === tool ) {
8384 this.pressed.setActive( false );
8389 * Get the closest tool to a jQuery.Event.
8391 * Only tool links are considered, which prevents other elements in the tool such as popups from
8392 * triggering tool group interactions.
8395 * @param {jQuery.Event} e
8396 * @return {OO.ui.Tool|null} Tool, `null` if none was found
8398 OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
8400 $item = $( e.target ).closest( '.oo-ui-tool-link' );
8402 if ( $item.length ) {
8403 tool = $item.parent().data( 'oo-ui-tool' );
8406 return tool && !tool.isDisabled() ? tool : null;
8410 * Handle tool registry register events.
8412 * If a tool is registered after the group is created, we must repopulate the list to account for:
8414 * - a tool being added that may be included
8415 * - a tool already included being overridden
8418 * @param {string} name Symbolic name of tool
8420 OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
8425 * Get the toolbar that contains the toolgroup.
8427 * @return {OO.ui.Toolbar} Toolbar that contains the toolgroup
8429 OO.ui.ToolGroup.prototype.getToolbar = function () {
8430 return this.toolbar;
8434 * Add and remove tools based on configuration.
8436 OO.ui.ToolGroup.prototype.populate = function () {
8437 var i, len, name, tool,
8438 toolFactory = this.toolbar.getToolFactory(),
8442 list = this.toolbar.getToolFactory().getTools(
8443 this.include, this.exclude, this.promote, this.demote
8446 // Build a list of needed tools
8447 for ( i = 0, len = list.length; i < len; i++ ) {
8451 toolFactory.lookup( name ) &&
8452 // Tool is available or is already in this group
8453 ( this.toolbar.isToolAvailable( name ) || this.tools[ name ] )
8455 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
8456 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
8457 this.toolbar.tools[ name ] = true;
8458 tool = this.tools[ name ];
8460 // Auto-initialize tools on first use
8461 this.tools[ name ] = tool = toolFactory.create( name, this );
8464 this.toolbar.reserveTool( tool );
8466 names[ name ] = true;
8469 // Remove tools that are no longer needed
8470 for ( name in this.tools ) {
8471 if ( !names[ name ] ) {
8472 this.tools[ name ].destroy();
8473 this.toolbar.releaseTool( this.tools[ name ] );
8474 remove.push( this.tools[ name ] );
8475 delete this.tools[ name ];
8478 if ( remove.length ) {
8479 this.removeItems( remove );
8481 // Update emptiness state
8483 this.$element.removeClass( 'oo-ui-toolGroup-empty' );
8485 this.$element.addClass( 'oo-ui-toolGroup-empty' );
8487 // Re-add tools (moving existing ones to new locations)
8488 this.addItems( add );
8489 // Disabled state may depend on items
8490 this.updateDisabled();
8494 * Destroy toolgroup.
8496 OO.ui.ToolGroup.prototype.destroy = function () {
8500 this.toolbar.getToolFactory().disconnect( this );
8501 for ( name in this.tools ) {
8502 this.toolbar.releaseTool( this.tools[ name ] );
8503 this.tools[ name ].disconnect( this ).destroy();
8504 delete this.tools[ name ];
8506 this.$element.remove();
8510 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
8511 * consists of a header that contains the dialog title, a body with the message, and a footer that
8512 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
8513 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
8515 * There are two basic types of message dialogs, confirmation and alert:
8517 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
8518 * more details about the consequences.
8519 * - **alert**: the dialog title describes which event occurred and the message provides more information
8520 * about why the event occurred.
8522 * The MessageDialog class specifies two actions: ‘accept’, the primary
8523 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
8524 * passing along the selected action.
8526 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
8529 * // Example: Creating and opening a message dialog window.
8530 * var messageDialog = new OO.ui.MessageDialog();
8532 * // Create and append a window manager.
8533 * var windowManager = new OO.ui.WindowManager();
8534 * $( 'body' ).append( windowManager.$element );
8535 * windowManager.addWindows( [ messageDialog ] );
8536 * // Open the window.
8537 * windowManager.openWindow( messageDialog, {
8538 * title: 'Basic message dialog',
8539 * message: 'This is the message'
8542 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
8545 * @extends OO.ui.Dialog
8548 * @param {Object} [config] Configuration options
8550 OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
8551 // Parent constructor
8552 OO.ui.MessageDialog.parent.call( this, config );
8555 this.verticalActionLayout = null;
8558 this.$element.addClass( 'oo-ui-messageDialog' );
8563 OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
8565 /* Static Properties */
8567 OO.ui.MessageDialog.static.name = 'message';
8569 OO.ui.MessageDialog.static.size = 'small';
8571 OO.ui.MessageDialog.static.verbose = false;
8576 * The title of a confirmation dialog describes what a progressive action will do. The
8577 * title of an alert dialog describes which event occurred.
8581 * @property {jQuery|string|Function|null}
8583 OO.ui.MessageDialog.static.title = null;
8586 * The message displayed in the dialog body.
8588 * A confirmation message describes the consequences of a progressive action. An alert
8589 * message describes why an event occurred.
8593 * @property {jQuery|string|Function|null}
8595 OO.ui.MessageDialog.static.message = null;
8597 // Note that OO.ui.alert() and OO.ui.confirm() rely on these.
8598 OO.ui.MessageDialog.static.actions = [
8599 { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
8600 { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
8608 OO.ui.MessageDialog.prototype.setManager = function ( manager ) {
8609 OO.ui.MessageDialog.parent.prototype.setManager.call( this, manager );
8612 this.manager.connect( this, {
8622 OO.ui.MessageDialog.prototype.onActionResize = function ( action ) {
8624 return OO.ui.MessageDialog.parent.prototype.onActionResize.call( this, action );
8628 * Handle window resized events.
8632 OO.ui.MessageDialog.prototype.onResize = function () {
8634 dialog.fitActions();
8635 // Wait for CSS transition to finish and do it again :(
8636 setTimeout( function () {
8637 dialog.fitActions();
8642 * Toggle action layout between vertical and horizontal.
8645 * @param {boolean} [value] Layout actions vertically, omit to toggle
8648 OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
8649 value = value === undefined ? !this.verticalActionLayout : !!value;
8651 if ( value !== this.verticalActionLayout ) {
8652 this.verticalActionLayout = value;
8654 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
8655 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
8664 OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
8666 return new OO.ui.Process( function () {
8667 this.close( { action: action } );
8670 return OO.ui.MessageDialog.parent.prototype.getActionProcess.call( this, action );
8676 * @param {Object} [data] Dialog opening data
8677 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
8678 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
8679 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
8680 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
8683 OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
8687 return OO.ui.MessageDialog.parent.prototype.getSetupProcess.call( this, data )
8688 .next( function () {
8689 this.title.setLabel(
8690 data.title !== undefined ? data.title : this.constructor.static.title
8692 this.message.setLabel(
8693 data.message !== undefined ? data.message : this.constructor.static.message
8695 this.message.$element.toggleClass(
8696 'oo-ui-messageDialog-message-verbose',
8697 data.verbose !== undefined ? data.verbose : this.constructor.static.verbose
8705 OO.ui.MessageDialog.prototype.getReadyProcess = function ( data ) {
8709 return OO.ui.MessageDialog.parent.prototype.getReadyProcess.call( this, data )
8710 .next( function () {
8711 // Focus the primary action button
8712 var actions = this.actions.get();
8713 actions = actions.filter( function ( action ) {
8714 return action.getFlags().indexOf( 'primary' ) > -1;
8716 if ( actions.length > 0 ) {
8717 actions[ 0 ].$button.focus();
8725 OO.ui.MessageDialog.prototype.getBodyHeight = function () {
8726 var bodyHeight, oldOverflow,
8727 $scrollable = this.container.$element;
8729 oldOverflow = $scrollable[ 0 ].style.overflow;
8730 $scrollable[ 0 ].style.overflow = 'hidden';
8732 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
8734 bodyHeight = this.text.$element.outerHeight( true );
8735 $scrollable[ 0 ].style.overflow = oldOverflow;
8743 OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
8744 var $scrollable = this.container.$element;
8745 OO.ui.MessageDialog.parent.prototype.setDimensions.call( this, dim );
8747 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
8748 // Need to do it after transition completes (250ms), add 50ms just in case.
8749 setTimeout( function () {
8750 var oldOverflow = $scrollable[ 0 ].style.overflow;
8751 $scrollable[ 0 ].style.overflow = 'hidden';
8753 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
8755 $scrollable[ 0 ].style.overflow = oldOverflow;
8764 OO.ui.MessageDialog.prototype.initialize = function () {
8766 OO.ui.MessageDialog.parent.prototype.initialize.call( this );
8769 this.$actions = $( '<div>' );
8770 this.container = new OO.ui.PanelLayout( {
8771 scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
8773 this.text = new OO.ui.PanelLayout( {
8774 padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
8776 this.message = new OO.ui.LabelWidget( {
8777 classes: [ 'oo-ui-messageDialog-message' ]
8781 this.title.$element.addClass( 'oo-ui-messageDialog-title' );
8782 this.$content.addClass( 'oo-ui-messageDialog-content' );
8783 this.container.$element.append( this.text.$element );
8784 this.text.$element.append( this.title.$element, this.message.$element );
8785 this.$body.append( this.container.$element );
8786 this.$actions.addClass( 'oo-ui-messageDialog-actions' );
8787 this.$foot.append( this.$actions );
8793 OO.ui.MessageDialog.prototype.attachActions = function () {
8794 var i, len, other, special, others;
8797 OO.ui.MessageDialog.parent.prototype.attachActions.call( this );
8799 special = this.actions.getSpecial();
8800 others = this.actions.getOthers();
8802 if ( special.safe ) {
8803 this.$actions.append( special.safe.$element );
8804 special.safe.toggleFramed( false );
8806 if ( others.length ) {
8807 for ( i = 0, len = others.length; i < len; i++ ) {
8808 other = others[ i ];
8809 this.$actions.append( other.$element );
8810 other.toggleFramed( false );
8813 if ( special.primary ) {
8814 this.$actions.append( special.primary.$element );
8815 special.primary.toggleFramed( false );
8818 if ( !this.isOpening() ) {
8819 // If the dialog is currently opening, this will be called automatically soon.
8820 // This also calls #fitActions.
8826 * Fit action actions into columns or rows.
8828 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
8832 OO.ui.MessageDialog.prototype.fitActions = function () {
8834 previous = this.verticalActionLayout,
8835 actions = this.actions.get();
8838 this.toggleVerticalActionLayout( false );
8839 for ( i = 0, len = actions.length; i < len; i++ ) {
8840 action = actions[ i ];
8841 if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
8842 this.toggleVerticalActionLayout( true );
8847 // Move the body out of the way of the foot
8848 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
8850 if ( this.verticalActionLayout !== previous ) {
8851 // We changed the layout, window height might need to be updated.
8857 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
8858 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
8859 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
8860 * relevant. The ProcessDialog class is always extended and customized with the actions and content
8861 * required for each process.
8863 * The process dialog box consists of a header that visually represents the ‘working’ state of long
8864 * processes with an animation. The header contains the dialog title as well as
8865 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
8866 * a ‘primary’ action on the right (e.g., ‘Done’).
8868 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
8869 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
8872 * // Example: Creating and opening a process dialog window.
8873 * function MyProcessDialog( config ) {
8874 * MyProcessDialog.parent.call( this, config );
8876 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
8878 * MyProcessDialog.static.title = 'Process dialog';
8879 * MyProcessDialog.static.actions = [
8880 * { action: 'save', label: 'Done', flags: 'primary' },
8881 * { label: 'Cancel', flags: 'safe' }
8884 * MyProcessDialog.prototype.initialize = function () {
8885 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
8886 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
8887 * 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>' );
8888 * this.$body.append( this.content.$element );
8890 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
8891 * var dialog = this;
8893 * return new OO.ui.Process( function () {
8894 * dialog.close( { action: action } );
8897 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
8900 * var windowManager = new OO.ui.WindowManager();
8901 * $( 'body' ).append( windowManager.$element );
8903 * var dialog = new MyProcessDialog();
8904 * windowManager.addWindows( [ dialog ] );
8905 * windowManager.openWindow( dialog );
8907 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
8911 * @extends OO.ui.Dialog
8914 * @param {Object} [config] Configuration options
8916 OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
8917 // Parent constructor
8918 OO.ui.ProcessDialog.parent.call( this, config );
8921 this.fitOnOpen = false;
8924 this.$element.addClass( 'oo-ui-processDialog' );
8929 OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
8934 * Handle dismiss button click events.
8940 OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
8945 * Handle retry button click events.
8947 * Hides errors and then tries again.
8951 OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
8953 this.executeAction( this.currentAction );
8959 OO.ui.ProcessDialog.prototype.onActionResize = function ( action ) {
8960 if ( this.actions.isSpecial( action ) ) {
8963 return OO.ui.ProcessDialog.parent.prototype.onActionResize.call( this, action );
8969 OO.ui.ProcessDialog.prototype.initialize = function () {
8971 OO.ui.ProcessDialog.parent.prototype.initialize.call( this );
8974 this.$navigation = $( '<div>' );
8975 this.$location = $( '<div>' );
8976 this.$safeActions = $( '<div>' );
8977 this.$primaryActions = $( '<div>' );
8978 this.$otherActions = $( '<div>' );
8979 this.dismissButton = new OO.ui.ButtonWidget( {
8980 label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
8982 this.retryButton = new OO.ui.ButtonWidget();
8983 this.$errors = $( '<div>' );
8984 this.$errorsTitle = $( '<div>' );
8987 this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
8988 this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
8991 this.title.$element.addClass( 'oo-ui-processDialog-title' );
8993 .append( this.title.$element )
8994 .addClass( 'oo-ui-processDialog-location' );
8995 this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
8996 this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
8997 this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
8999 .addClass( 'oo-ui-processDialog-errors-title' )
9000 .text( OO.ui.msg( 'ooui-dialog-process-error' ) );
9002 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
9003 .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
9005 .addClass( 'oo-ui-processDialog-content' )
9006 .append( this.$errors );
9008 .addClass( 'oo-ui-processDialog-navigation' )
9009 .append( this.$safeActions, this.$location, this.$primaryActions );
9010 this.$head.append( this.$navigation );
9011 this.$foot.append( this.$otherActions );
9017 OO.ui.ProcessDialog.prototype.getActionWidgets = function ( actions ) {
9018 var i, len, widgets = [];
9019 for ( i = 0, len = actions.length; i < len; i++ ) {
9021 new OO.ui.ActionWidget( $.extend( { framed: true }, actions[ i ] ) )
9030 OO.ui.ProcessDialog.prototype.attachActions = function () {
9031 var i, len, other, special, others;
9034 OO.ui.ProcessDialog.parent.prototype.attachActions.call( this );
9036 special = this.actions.getSpecial();
9037 others = this.actions.getOthers();
9038 if ( special.primary ) {
9039 this.$primaryActions.append( special.primary.$element );
9041 for ( i = 0, len = others.length; i < len; i++ ) {
9042 other = others[ i ];
9043 this.$otherActions.append( other.$element );
9045 if ( special.safe ) {
9046 this.$safeActions.append( special.safe.$element );
9050 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
9056 OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
9058 return OO.ui.ProcessDialog.parent.prototype.executeAction.call( this, action )
9059 .fail( function ( errors ) {
9060 process.showErrors( errors || [] );
9067 OO.ui.ProcessDialog.prototype.setDimensions = function () {
9069 OO.ui.ProcessDialog.parent.prototype.setDimensions.apply( this, arguments );
9075 * Fit label between actions.
9080 OO.ui.ProcessDialog.prototype.fitLabel = function () {
9081 var safeWidth, primaryWidth, biggerWidth, labelWidth, navigationWidth, leftWidth, rightWidth,
9082 size = this.getSizeProperties();
9084 if ( typeof size.width !== 'number' ) {
9085 if ( this.isOpened() ) {
9086 navigationWidth = this.$head.width() - 20;
9087 } else if ( this.isOpening() ) {
9088 if ( !this.fitOnOpen ) {
9089 // Size is relative and the dialog isn't open yet, so wait.
9090 this.manager.opening.done( this.fitLabel.bind( this ) );
9091 this.fitOnOpen = true;
9098 navigationWidth = size.width - 20;
9101 safeWidth = this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0;
9102 primaryWidth = this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0;
9103 biggerWidth = Math.max( safeWidth, primaryWidth );
9105 labelWidth = this.title.$element.width();
9107 if ( 2 * biggerWidth + labelWidth < navigationWidth ) {
9108 // We have enough space to center the label
9109 leftWidth = rightWidth = biggerWidth;
9111 // Let's hope we at least have enough space not to overlap, because we can't wrap the label…
9112 if ( this.getDir() === 'ltr' ) {
9113 leftWidth = safeWidth;
9114 rightWidth = primaryWidth;
9116 leftWidth = primaryWidth;
9117 rightWidth = safeWidth;
9121 this.$location.css( { paddingLeft: leftWidth, paddingRight: rightWidth } );
9127 * Handle errors that occurred during accept or reject processes.
9130 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
9132 OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
9133 var i, len, $item, actions,
9139 if ( errors instanceof OO.ui.Error ) {
9140 errors = [ errors ];
9143 for ( i = 0, len = errors.length; i < len; i++ ) {
9144 if ( !errors[ i ].isRecoverable() ) {
9145 recoverable = false;
9147 if ( errors[ i ].isWarning() ) {
9150 $item = $( '<div>' )
9151 .addClass( 'oo-ui-processDialog-error' )
9152 .append( errors[ i ].getMessage() );
9153 items.push( $item[ 0 ] );
9155 this.$errorItems = $( items );
9156 if ( recoverable ) {
9157 abilities[ this.currentAction ] = true;
9158 // Copy the flags from the first matching action
9159 actions = this.actions.get( { actions: this.currentAction } );
9160 if ( actions.length ) {
9161 this.retryButton.clearFlags().setFlags( actions[ 0 ].getFlags() );
9164 abilities[ this.currentAction ] = false;
9165 this.actions.setAbilities( abilities );
9168 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
9170 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
9172 this.retryButton.toggle( recoverable );
9173 this.$errorsTitle.after( this.$errorItems );
9174 this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
9182 OO.ui.ProcessDialog.prototype.hideErrors = function () {
9183 this.$errors.addClass( 'oo-ui-element-hidden' );
9184 if ( this.$errorItems ) {
9185 this.$errorItems.remove();
9186 this.$errorItems = null;
9193 OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) {
9195 return OO.ui.ProcessDialog.parent.prototype.getTeardownProcess.call( this, data )
9196 .first( function () {
9197 // Make sure to hide errors
9199 this.fitOnOpen = false;
9204 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
9205 * which is a widget that is specified by reference before any optional configuration settings.
9207 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
9209 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9210 * A left-alignment is used for forms with many fields.
9211 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9212 * A right-alignment is used for long but familiar forms which users tab through,
9213 * verifying the current field with a quick glance at the label.
9214 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9215 * that users fill out from top to bottom.
9216 * - **inline**: The label is placed after the field-widget and aligned to the left.
9217 * An inline-alignment is best used with checkboxes or radio buttons.
9219 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
9220 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
9222 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9224 * @extends OO.ui.Layout
9225 * @mixins OO.ui.mixin.LabelElement
9226 * @mixins OO.ui.mixin.TitledElement
9229 * @param {OO.ui.Widget} fieldWidget Field widget
9230 * @param {Object} [config] Configuration options
9231 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
9232 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
9233 * The array may contain strings or OO.ui.HtmlSnippet instances.
9234 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
9235 * The array may contain strings or OO.ui.HtmlSnippet instances.
9236 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
9237 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
9238 * For important messages, you are advised to use `notices`, as they are always shown.
9240 * @throws {Error} An error is thrown if no widget is specified
9242 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
9243 var hasInputWidget, div;
9245 // Allow passing positional parameters inside the config object
9246 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
9247 config = fieldWidget;
9248 fieldWidget = config.fieldWidget;
9251 // Make sure we have required constructor arguments
9252 if ( fieldWidget === undefined ) {
9253 throw new Error( 'Widget not found' );
9256 hasInputWidget = fieldWidget.constructor.static.supportsSimpleLabel;
9258 // Configuration initialization
9259 config = $.extend( { align: 'left' }, config );
9261 // Parent constructor
9262 OO.ui.FieldLayout.parent.call( this, config );
9264 // Mixin constructors
9265 OO.ui.mixin.LabelElement.call( this, config );
9266 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
9269 this.fieldWidget = fieldWidget;
9272 this.$field = $( '<div>' );
9273 this.$messages = $( '<ul>' );
9274 this.$body = $( '<' + ( hasInputWidget ? 'label' : 'div' ) + '>' );
9276 if ( config.help ) {
9277 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
9278 classes: [ 'oo-ui-fieldLayout-help' ],
9284 if ( config.help instanceof OO.ui.HtmlSnippet ) {
9285 div.html( config.help.toString() );
9287 div.text( config.help );
9289 this.popupButtonWidget.getPopup().$body.append(
9290 div.addClass( 'oo-ui-fieldLayout-help-content' )
9292 this.$help = this.popupButtonWidget.$element;
9294 this.$help = $( [] );
9298 if ( hasInputWidget ) {
9299 this.$label.on( 'click', this.onLabelClick.bind( this ) );
9301 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
9305 .addClass( 'oo-ui-fieldLayout' )
9306 .append( this.$help, this.$body );
9307 this.$body.addClass( 'oo-ui-fieldLayout-body' );
9308 this.$messages.addClass( 'oo-ui-fieldLayout-messages' );
9310 .addClass( 'oo-ui-fieldLayout-field' )
9311 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget.isDisabled() )
9312 .append( this.fieldWidget.$element );
9314 this.setErrors( config.errors || [] );
9315 this.setNotices( config.notices || [] );
9316 this.setAlignment( config.align );
9321 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
9322 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement );
9323 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement );
9328 * Handle field disable events.
9331 * @param {boolean} value Field is disabled
9333 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
9334 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
9338 * Handle label mouse click events.
9341 * @param {jQuery.Event} e Mouse click event
9343 OO.ui.FieldLayout.prototype.onLabelClick = function () {
9344 this.fieldWidget.simulateLabelClick();
9349 * Get the widget contained by the field.
9351 * @return {OO.ui.Widget} Field widget
9353 OO.ui.FieldLayout.prototype.getField = function () {
9354 return this.fieldWidget;
9359 * @param {string} kind 'error' or 'notice'
9360 * @param {string|OO.ui.HtmlSnippet} text
9363 OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) {
9364 var $listItem, $icon, message;
9365 $listItem = $( '<li>' );
9366 if ( kind === 'error' ) {
9367 $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element;
9368 } else if ( kind === 'notice' ) {
9369 $icon = new OO.ui.IconWidget( { icon: 'info' } ).$element;
9373 message = new OO.ui.LabelWidget( { label: text } );
9375 .append( $icon, message.$element )
9376 .addClass( 'oo-ui-fieldLayout-messages-' + kind );
9381 * Set the field alignment mode.
9384 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
9387 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
9388 if ( value !== this.align ) {
9389 // Default to 'left'
9390 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
9394 if ( value === 'inline' ) {
9395 this.$body.append( this.$field, this.$label );
9397 this.$body.append( this.$label, this.$field );
9399 // Set classes. The following classes can be used here:
9400 // * oo-ui-fieldLayout-align-left
9401 // * oo-ui-fieldLayout-align-right
9402 // * oo-ui-fieldLayout-align-top
9403 // * oo-ui-fieldLayout-align-inline
9405 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
9407 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
9415 * Set the list of error messages.
9417 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
9418 * The array may contain strings or OO.ui.HtmlSnippet instances.
9421 OO.ui.FieldLayout.prototype.setErrors = function ( errors ) {
9422 this.errors = errors.slice();
9423 this.updateMessages();
9428 * Set the list of notice messages.
9430 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
9431 * The array may contain strings or OO.ui.HtmlSnippet instances.
9434 OO.ui.FieldLayout.prototype.setNotices = function ( notices ) {
9435 this.notices = notices.slice();
9436 this.updateMessages();
9441 * Update the rendering of error and notice messages.
9445 OO.ui.FieldLayout.prototype.updateMessages = function () {
9447 this.$messages.empty();
9449 if ( this.errors.length || this.notices.length ) {
9450 this.$body.after( this.$messages );
9452 this.$messages.remove();
9456 for ( i = 0; i < this.notices.length; i++ ) {
9457 this.$messages.append( this.makeMessage( 'notice', this.notices[ i ] ) );
9459 for ( i = 0; i < this.errors.length; i++ ) {
9460 this.$messages.append( this.makeMessage( 'error', this.errors[ i ] ) );
9465 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
9466 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
9467 * is required and is specified before any optional configuration settings.
9469 * Labels can be aligned in one of four ways:
9471 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9472 * A left-alignment is used for forms with many fields.
9473 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9474 * A right-alignment is used for long but familiar forms which users tab through,
9475 * verifying the current field with a quick glance at the label.
9476 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9477 * that users fill out from top to bottom.
9478 * - **inline**: The label is placed after the field-widget and aligned to the left.
9479 * An inline-alignment is best used with checkboxes or radio buttons.
9481 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
9482 * text is specified.
9485 * // Example of an ActionFieldLayout
9486 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
9487 * new OO.ui.TextInputWidget( {
9488 * placeholder: 'Field widget'
9490 * new OO.ui.ButtonWidget( {
9494 * label: 'An ActionFieldLayout. This label is aligned top',
9496 * help: 'This is help text'
9500 * $( 'body' ).append( actionFieldLayout.$element );
9503 * @extends OO.ui.FieldLayout
9506 * @param {OO.ui.Widget} fieldWidget Field widget
9507 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
9509 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
9510 // Allow passing positional parameters inside the config object
9511 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
9512 config = fieldWidget;
9513 fieldWidget = config.fieldWidget;
9514 buttonWidget = config.buttonWidget;
9517 // Parent constructor
9518 OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config );
9521 this.buttonWidget = buttonWidget;
9522 this.$button = $( '<div>' );
9523 this.$input = $( '<div>' );
9527 .addClass( 'oo-ui-actionFieldLayout' );
9529 .addClass( 'oo-ui-actionFieldLayout-button' )
9530 .append( this.buttonWidget.$element );
9532 .addClass( 'oo-ui-actionFieldLayout-input' )
9533 .append( this.fieldWidget.$element );
9535 .append( this.$input, this.$button );
9540 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
9543 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
9544 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
9545 * configured with a label as well. For more information and examples,
9546 * please see the [OOjs UI documentation on MediaWiki][1].
9549 * // Example of a fieldset layout
9550 * var input1 = new OO.ui.TextInputWidget( {
9551 * placeholder: 'A text input field'
9554 * var input2 = new OO.ui.TextInputWidget( {
9555 * placeholder: 'A text input field'
9558 * var fieldset = new OO.ui.FieldsetLayout( {
9559 * label: 'Example of a fieldset layout'
9562 * fieldset.addItems( [
9563 * new OO.ui.FieldLayout( input1, {
9564 * label: 'Field One'
9566 * new OO.ui.FieldLayout( input2, {
9567 * label: 'Field Two'
9570 * $( 'body' ).append( fieldset.$element );
9572 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9575 * @extends OO.ui.Layout
9576 * @mixins OO.ui.mixin.IconElement
9577 * @mixins OO.ui.mixin.LabelElement
9578 * @mixins OO.ui.mixin.GroupElement
9581 * @param {Object} [config] Configuration options
9582 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
9584 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
9585 // Configuration initialization
9586 config = config || {};
9588 // Parent constructor
9589 OO.ui.FieldsetLayout.parent.call( this, config );
9591 // Mixin constructors
9592 OO.ui.mixin.IconElement.call( this, config );
9593 OO.ui.mixin.LabelElement.call( this, config );
9594 OO.ui.mixin.GroupElement.call( this, config );
9596 if ( config.help ) {
9597 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
9598 classes: [ 'oo-ui-fieldsetLayout-help' ],
9603 this.popupButtonWidget.getPopup().$body.append(
9605 .text( config.help )
9606 .addClass( 'oo-ui-fieldsetLayout-help-content' )
9608 this.$help = this.popupButtonWidget.$element;
9610 this.$help = $( [] );
9615 .addClass( 'oo-ui-fieldsetLayout' )
9616 .prepend( this.$help, this.$icon, this.$label, this.$group );
9617 if ( Array.isArray( config.items ) ) {
9618 this.addItems( config.items );
9624 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
9625 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement );
9626 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement );
9627 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement );
9630 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
9631 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
9632 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
9633 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9635 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
9636 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
9637 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
9638 * some fancier controls. Some controls have both regular and InputWidget variants, for example
9639 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
9640 * often have simplified APIs to match the capabilities of HTML forms.
9641 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
9643 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
9644 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9647 * // Example of a form layout that wraps a fieldset layout
9648 * var input1 = new OO.ui.TextInputWidget( {
9649 * placeholder: 'Username'
9651 * var input2 = new OO.ui.TextInputWidget( {
9652 * placeholder: 'Password',
9655 * var submit = new OO.ui.ButtonInputWidget( {
9659 * var fieldset = new OO.ui.FieldsetLayout( {
9660 * label: 'A form layout'
9662 * fieldset.addItems( [
9663 * new OO.ui.FieldLayout( input1, {
9664 * label: 'Username',
9667 * new OO.ui.FieldLayout( input2, {
9668 * label: 'Password',
9671 * new OO.ui.FieldLayout( submit )
9673 * var form = new OO.ui.FormLayout( {
9674 * items: [ fieldset ],
9675 * action: '/api/formhandler',
9678 * $( 'body' ).append( form.$element );
9681 * @extends OO.ui.Layout
9682 * @mixins OO.ui.mixin.GroupElement
9685 * @param {Object} [config] Configuration options
9686 * @cfg {string} [method] HTML form `method` attribute
9687 * @cfg {string} [action] HTML form `action` attribute
9688 * @cfg {string} [enctype] HTML form `enctype` attribute
9689 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
9691 OO.ui.FormLayout = function OoUiFormLayout( config ) {
9692 // Configuration initialization
9693 config = config || {};
9695 // Parent constructor
9696 OO.ui.FormLayout.parent.call( this, config );
9698 // Mixin constructors
9699 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
9702 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
9704 // Make sure the action is safe
9705 if ( config.action !== undefined && !OO.ui.isSafeUrl( config.action ) ) {
9706 throw new Error( 'Potentially unsafe action provided: ' + config.action );
9711 .addClass( 'oo-ui-formLayout' )
9713 method: config.method,
9714 action: config.action,
9715 enctype: config.enctype
9717 if ( Array.isArray( config.items ) ) {
9718 this.addItems( config.items );
9724 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
9725 OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement );
9730 * A 'submit' event is emitted when the form is submitted.
9735 /* Static Properties */
9737 OO.ui.FormLayout.static.tagName = 'form';
9742 * Handle form submit events.
9745 * @param {jQuery.Event} e Submit event
9748 OO.ui.FormLayout.prototype.onFormSubmit = function () {
9749 if ( this.emit( 'submit' ) ) {
9755 * 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)
9756 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
9759 * var menuLayout = new OO.ui.MenuLayout( {
9762 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9763 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9764 * select = new OO.ui.SelectWidget( {
9766 * new OO.ui.OptionWidget( {
9770 * new OO.ui.OptionWidget( {
9774 * new OO.ui.OptionWidget( {
9778 * new OO.ui.OptionWidget( {
9783 * } ).on( 'select', function ( item ) {
9784 * menuLayout.setMenuPosition( item.getData() );
9787 * menuLayout.$menu.append(
9788 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
9790 * menuLayout.$content.append(
9791 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
9793 * $( 'body' ).append( menuLayout.$element );
9795 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
9796 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
9797 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
9800 * .oo-ui-menuLayout-menu {
9804 * .oo-ui-menuLayout-content {
9812 * @extends OO.ui.Layout
9815 * @param {Object} [config] Configuration options
9816 * @cfg {boolean} [showMenu=true] Show menu
9817 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
9819 OO.ui.MenuLayout = function OoUiMenuLayout( config ) {
9820 // Configuration initialization
9821 config = $.extend( {
9823 menuPosition: 'before'
9826 // Parent constructor
9827 OO.ui.MenuLayout.parent.call( this, config );
9832 * @property {jQuery}
9834 this.$menu = $( '<div>' );
9838 * @property {jQuery}
9840 this.$content = $( '<div>' );
9844 .addClass( 'oo-ui-menuLayout-menu' );
9845 this.$content.addClass( 'oo-ui-menuLayout-content' );
9847 .addClass( 'oo-ui-menuLayout' )
9848 .append( this.$content, this.$menu );
9849 this.setMenuPosition( config.menuPosition );
9850 this.toggleMenu( config.showMenu );
9855 OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout );
9862 * @param {boolean} showMenu Show menu, omit to toggle
9865 OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) {
9866 showMenu = showMenu === undefined ? !this.showMenu : !!showMenu;
9868 if ( this.showMenu !== showMenu ) {
9869 this.showMenu = showMenu;
9871 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu )
9872 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu );
9879 * Check if menu is visible
9881 * @return {boolean} Menu is visible
9883 OO.ui.MenuLayout.prototype.isMenuVisible = function () {
9884 return this.showMenu;
9888 * Set menu position.
9890 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
9891 * @throws {Error} If position value is not supported
9894 OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) {
9895 this.$element.removeClass( 'oo-ui-menuLayout-' + this.menuPosition );
9896 this.menuPosition = position;
9897 this.$element.addClass( 'oo-ui-menuLayout-' + position );
9903 * Get menu position.
9905 * @return {string} Menu position
9907 OO.ui.MenuLayout.prototype.getMenuPosition = function () {
9908 return this.menuPosition;
9912 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
9913 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
9914 * through the pages and select which one to display. By default, only one page is
9915 * displayed at a time and the outline is hidden. When a user navigates to a new page,
9916 * the booklet layout automatically focuses on the first focusable element, unless the
9917 * default setting is changed. Optionally, booklets can be configured to show
9918 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
9921 * // Example of a BookletLayout that contains two PageLayouts.
9923 * function PageOneLayout( name, config ) {
9924 * PageOneLayout.parent.call( this, name, config );
9925 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
9927 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
9928 * PageOneLayout.prototype.setupOutlineItem = function () {
9929 * this.outlineItem.setLabel( 'Page One' );
9932 * function PageTwoLayout( name, config ) {
9933 * PageTwoLayout.parent.call( this, name, config );
9934 * this.$element.append( '<p>Second page</p>' );
9936 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
9937 * PageTwoLayout.prototype.setupOutlineItem = function () {
9938 * this.outlineItem.setLabel( 'Page Two' );
9941 * var page1 = new PageOneLayout( 'one' ),
9942 * page2 = new PageTwoLayout( 'two' );
9944 * var booklet = new OO.ui.BookletLayout( {
9948 * booklet.addPages ( [ page1, page2 ] );
9949 * $( 'body' ).append( booklet.$element );
9952 * @extends OO.ui.MenuLayout
9955 * @param {Object} [config] Configuration options
9956 * @cfg {boolean} [continuous=false] Show all pages, one after another
9957 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
9958 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
9959 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
9961 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
9962 // Configuration initialization
9963 config = config || {};
9965 // Parent constructor
9966 OO.ui.BookletLayout.parent.call( this, config );
9969 this.currentPageName = null;
9971 this.ignoreFocus = false;
9972 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
9973 this.$content.append( this.stackLayout.$element );
9974 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
9975 this.outlineVisible = false;
9976 this.outlined = !!config.outlined;
9977 if ( this.outlined ) {
9978 this.editable = !!config.editable;
9979 this.outlineControlsWidget = null;
9980 this.outlineSelectWidget = new OO.ui.OutlineSelectWidget();
9981 this.outlinePanel = new OO.ui.PanelLayout( { scrollable: true } );
9982 this.$menu.append( this.outlinePanel.$element );
9983 this.outlineVisible = true;
9984 if ( this.editable ) {
9985 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
9986 this.outlineSelectWidget
9990 this.toggleMenu( this.outlined );
9993 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
9994 if ( this.outlined ) {
9995 this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
9996 this.scrolling = false;
9997 this.stackLayout.connect( this, { visibleItemChange: 'onStackLayoutVisibleItemChange' } );
9999 if ( this.autoFocus ) {
10000 // Event 'focus' does not bubble, but 'focusin' does
10001 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
10005 this.$element.addClass( 'oo-ui-bookletLayout' );
10006 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
10007 if ( this.outlined ) {
10008 this.outlinePanel.$element
10009 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
10010 .append( this.outlineSelectWidget.$element );
10011 if ( this.editable ) {
10012 this.outlinePanel.$element
10013 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
10014 .append( this.outlineControlsWidget.$element );
10021 OO.inheritClass( OO.ui.BookletLayout, OO.ui.MenuLayout );
10026 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
10028 * @param {OO.ui.PageLayout} page Current page
10032 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
10035 * @param {OO.ui.PageLayout[]} page Added pages
10036 * @param {number} index Index pages were added at
10040 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
10041 * {@link #removePages removed} from the booklet.
10044 * @param {OO.ui.PageLayout[]} pages Removed pages
10050 * Handle stack layout focus.
10053 * @param {jQuery.Event} e Focusin event
10055 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
10058 // Find the page that an element was focused within
10059 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
10060 for ( name in this.pages ) {
10061 // Check for page match, exclude current page to find only page changes
10062 if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) {
10063 this.setPage( name );
10070 * Handle visibleItemChange events from the stackLayout
10072 * The next visible page is set as the current page by selecting it
10075 * @param {OO.ui.PageLayout} page The next visible page in the layout
10077 OO.ui.BookletLayout.prototype.onStackLayoutVisibleItemChange = function ( page ) {
10078 // Set a flag to so that the resulting call to #onStackLayoutSet doesn't
10079 // try and scroll the item into view again.
10080 this.scrolling = true;
10081 this.outlineSelectWidget.selectItemByData( page.getName() );
10082 this.scrolling = false;
10086 * Handle stack layout set events.
10089 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
10091 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
10093 if ( !this.scrolling && page ) {
10094 page.scrollElementIntoView( { complete: function () {
10095 if ( layout.autoFocus ) {
10103 * Focus the first input in the current page.
10105 * If no page is selected, the first selectable page will be selected.
10106 * If the focus is already in an element on the current page, nothing will happen.
10107 * @param {number} [itemIndex] A specific item to focus on
10109 OO.ui.BookletLayout.prototype.focus = function ( itemIndex ) {
10111 items = this.stackLayout.getItems();
10113 if ( itemIndex !== undefined && items[ itemIndex ] ) {
10114 page = items[ itemIndex ];
10116 page = this.stackLayout.getCurrentItem();
10119 if ( !page && this.outlined ) {
10120 this.selectFirstSelectablePage();
10121 page = this.stackLayout.getCurrentItem();
10126 // Only change the focus if is not already in the current page
10127 if ( !OO.ui.contains( page.$element[ 0 ], this.getElementDocument().activeElement, true ) ) {
10133 * Find the first focusable input in the booklet layout and focus
10136 OO.ui.BookletLayout.prototype.focusFirstFocusable = function () {
10137 OO.ui.findFocusable( this.stackLayout.$element ).focus();
10141 * Handle outline widget select events.
10144 * @param {OO.ui.OptionWidget|null} item Selected item
10146 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
10148 this.setPage( item.getData() );
10153 * Check if booklet has an outline.
10155 * @return {boolean} Booklet has an outline
10157 OO.ui.BookletLayout.prototype.isOutlined = function () {
10158 return this.outlined;
10162 * Check if booklet has editing controls.
10164 * @return {boolean} Booklet is editable
10166 OO.ui.BookletLayout.prototype.isEditable = function () {
10167 return this.editable;
10171 * Check if booklet has a visible outline.
10173 * @return {boolean} Outline is visible
10175 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
10176 return this.outlined && this.outlineVisible;
10180 * Hide or show the outline.
10182 * @param {boolean} [show] Show outline, omit to invert current state
10185 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
10186 if ( this.outlined ) {
10187 show = show === undefined ? !this.outlineVisible : !!show;
10188 this.outlineVisible = show;
10189 this.toggleMenu( show );
10196 * Get the page closest to the specified page.
10198 * @param {OO.ui.PageLayout} page Page to use as a reference point
10199 * @return {OO.ui.PageLayout|null} Page closest to the specified page
10201 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
10202 var next, prev, level,
10203 pages = this.stackLayout.getItems(),
10204 index = pages.indexOf( page );
10206 if ( index !== -1 ) {
10207 next = pages[ index + 1 ];
10208 prev = pages[ index - 1 ];
10209 // Prefer adjacent pages at the same level
10210 if ( this.outlined ) {
10211 level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
10214 level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
10220 level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
10226 return prev || next || null;
10230 * Get the outline widget.
10232 * If the booklet is not outlined, the method will return `null`.
10234 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
10236 OO.ui.BookletLayout.prototype.getOutline = function () {
10237 return this.outlineSelectWidget;
10241 * Get the outline controls widget.
10243 * If the outline is not editable, the method will return `null`.
10245 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
10247 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
10248 return this.outlineControlsWidget;
10252 * Get a page by its symbolic name.
10254 * @param {string} name Symbolic name of page
10255 * @return {OO.ui.PageLayout|undefined} Page, if found
10257 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
10258 return this.pages[ name ];
10262 * Get the current page.
10264 * @return {OO.ui.PageLayout|undefined} Current page, if found
10266 OO.ui.BookletLayout.prototype.getCurrentPage = function () {
10267 var name = this.getCurrentPageName();
10268 return name ? this.getPage( name ) : undefined;
10272 * Get the symbolic name of the current page.
10274 * @return {string|null} Symbolic name of the current page
10276 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
10277 return this.currentPageName;
10281 * Add pages to the booklet layout
10283 * When pages are added with the same names as existing pages, the existing pages will be
10284 * automatically removed before the new pages are added.
10286 * @param {OO.ui.PageLayout[]} pages Pages to add
10287 * @param {number} index Index of the insertion point
10291 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
10292 var i, len, name, page, item, currentIndex,
10293 stackLayoutPages = this.stackLayout.getItems(),
10297 // Remove pages with same names
10298 for ( i = 0, len = pages.length; i < len; i++ ) {
10300 name = page.getName();
10302 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
10303 // Correct the insertion index
10304 currentIndex = stackLayoutPages.indexOf( this.pages[ name ] );
10305 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
10308 remove.push( this.pages[ name ] );
10311 if ( remove.length ) {
10312 this.removePages( remove );
10316 for ( i = 0, len = pages.length; i < len; i++ ) {
10318 name = page.getName();
10319 this.pages[ page.getName() ] = page;
10320 if ( this.outlined ) {
10321 item = new OO.ui.OutlineOptionWidget( { data: name } );
10322 page.setOutlineItem( item );
10323 items.push( item );
10327 if ( this.outlined && items.length ) {
10328 this.outlineSelectWidget.addItems( items, index );
10329 this.selectFirstSelectablePage();
10331 this.stackLayout.addItems( pages, index );
10332 this.emit( 'add', pages, index );
10338 * Remove the specified pages from the booklet layout.
10340 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
10342 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
10346 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
10347 var i, len, name, page,
10350 for ( i = 0, len = pages.length; i < len; i++ ) {
10352 name = page.getName();
10353 delete this.pages[ name ];
10354 if ( this.outlined ) {
10355 items.push( this.outlineSelectWidget.getItemFromData( name ) );
10356 page.setOutlineItem( null );
10359 if ( this.outlined && items.length ) {
10360 this.outlineSelectWidget.removeItems( items );
10361 this.selectFirstSelectablePage();
10363 this.stackLayout.removeItems( pages );
10364 this.emit( 'remove', pages );
10370 * Clear all pages from the booklet layout.
10372 * To remove only a subset of pages from the booklet, use the #removePages method.
10377 OO.ui.BookletLayout.prototype.clearPages = function () {
10379 pages = this.stackLayout.getItems();
10382 this.currentPageName = null;
10383 if ( this.outlined ) {
10384 this.outlineSelectWidget.clearItems();
10385 for ( i = 0, len = pages.length; i < len; i++ ) {
10386 pages[ i ].setOutlineItem( null );
10389 this.stackLayout.clearItems();
10391 this.emit( 'remove', pages );
10397 * Set the current page by symbolic name.
10400 * @param {string} name Symbolic name of page
10402 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
10405 page = this.pages[ name ],
10406 previousPage = this.currentPageName && this.pages[ this.currentPageName ];
10408 if ( name !== this.currentPageName ) {
10409 if ( this.outlined ) {
10410 selectedItem = this.outlineSelectWidget.getSelectedItem();
10411 if ( selectedItem && selectedItem.getData() !== name ) {
10412 this.outlineSelectWidget.selectItemByData( name );
10416 if ( previousPage ) {
10417 previousPage.setActive( false );
10418 // Blur anything focused if the next page doesn't have anything focusable.
10419 // This is not needed if the next page has something focusable (because once it is focused
10420 // this blur happens automatically). If the layout is non-continuous, this check is
10421 // meaningless because the next page is not visible yet and thus can't hold focus.
10424 this.stackLayout.continuous &&
10425 OO.ui.findFocusable( page.$element ).length !== 0
10427 $focused = previousPage.$element.find( ':focus' );
10428 if ( $focused.length ) {
10429 $focused[ 0 ].blur();
10433 this.currentPageName = name;
10434 page.setActive( true );
10435 this.stackLayout.setItem( page );
10436 if ( !this.stackLayout.continuous && previousPage ) {
10437 // This should not be necessary, since any inputs on the previous page should have been
10438 // blurred when it was hidden, but browsers are not very consistent about this.
10439 $focused = previousPage.$element.find( ':focus' );
10440 if ( $focused.length ) {
10441 $focused[ 0 ].blur();
10444 this.emit( 'set', page );
10450 * Select the first selectable page.
10454 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
10455 if ( !this.outlineSelectWidget.getSelectedItem() ) {
10456 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() );
10463 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
10464 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
10465 * select which one to display. By default, only one card is displayed at a time. When a user
10466 * navigates to a new card, the index layout automatically focuses on the first focusable element,
10467 * unless the default setting is changed.
10469 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
10472 * // Example of a IndexLayout that contains two CardLayouts.
10474 * function CardOneLayout( name, config ) {
10475 * CardOneLayout.parent.call( this, name, config );
10476 * this.$element.append( '<p>First card</p>' );
10478 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
10479 * CardOneLayout.prototype.setupTabItem = function () {
10480 * this.tabItem.setLabel( 'Card one' );
10483 * var card1 = new CardOneLayout( 'one' ),
10484 * card2 = new CardLayout( 'two', { label: 'Card two' } );
10486 * card2.$element.append( '<p>Second card</p>' );
10488 * var index = new OO.ui.IndexLayout();
10490 * index.addCards ( [ card1, card2 ] );
10491 * $( 'body' ).append( index.$element );
10494 * @extends OO.ui.MenuLayout
10497 * @param {Object} [config] Configuration options
10498 * @cfg {boolean} [continuous=false] Show all cards, one after another
10499 * @cfg {boolean} [expanded=true] Expand the content panel to fill the entire parent element.
10500 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
10502 OO.ui.IndexLayout = function OoUiIndexLayout( config ) {
10503 // Configuration initialization
10504 config = $.extend( {}, config, { menuPosition: 'top' } );
10506 // Parent constructor
10507 OO.ui.IndexLayout.parent.call( this, config );
10510 this.currentCardName = null;
10512 this.ignoreFocus = false;
10513 this.stackLayout = new OO.ui.StackLayout( {
10514 continuous: !!config.continuous,
10515 expanded: config.expanded
10517 this.$content.append( this.stackLayout.$element );
10518 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
10520 this.tabSelectWidget = new OO.ui.TabSelectWidget();
10521 this.tabPanel = new OO.ui.PanelLayout();
10522 this.$menu.append( this.tabPanel.$element );
10524 this.toggleMenu( true );
10527 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
10528 this.tabSelectWidget.connect( this, { select: 'onTabSelectWidgetSelect' } );
10529 if ( this.autoFocus ) {
10530 // Event 'focus' does not bubble, but 'focusin' does
10531 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
10535 this.$element.addClass( 'oo-ui-indexLayout' );
10536 this.stackLayout.$element.addClass( 'oo-ui-indexLayout-stackLayout' );
10537 this.tabPanel.$element
10538 .addClass( 'oo-ui-indexLayout-tabPanel' )
10539 .append( this.tabSelectWidget.$element );
10544 OO.inheritClass( OO.ui.IndexLayout, OO.ui.MenuLayout );
10549 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
10551 * @param {OO.ui.CardLayout} card Current card
10555 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
10558 * @param {OO.ui.CardLayout[]} card Added cards
10559 * @param {number} index Index cards were added at
10563 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
10564 * {@link #removeCards removed} from the index.
10567 * @param {OO.ui.CardLayout[]} cards Removed cards
10573 * Handle stack layout focus.
10576 * @param {jQuery.Event} e Focusin event
10578 OO.ui.IndexLayout.prototype.onStackLayoutFocus = function ( e ) {
10581 // Find the card that an element was focused within
10582 $target = $( e.target ).closest( '.oo-ui-cardLayout' );
10583 for ( name in this.cards ) {
10584 // Check for card match, exclude current card to find only card changes
10585 if ( this.cards[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentCardName ) {
10586 this.setCard( name );
10593 * Handle stack layout set events.
10596 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
10598 OO.ui.IndexLayout.prototype.onStackLayoutSet = function ( card ) {
10601 card.scrollElementIntoView( { complete: function () {
10602 if ( layout.autoFocus ) {
10610 * Focus the first input in the current card.
10612 * If no card is selected, the first selectable card will be selected.
10613 * If the focus is already in an element on the current card, nothing will happen.
10614 * @param {number} [itemIndex] A specific item to focus on
10616 OO.ui.IndexLayout.prototype.focus = function ( itemIndex ) {
10618 items = this.stackLayout.getItems();
10620 if ( itemIndex !== undefined && items[ itemIndex ] ) {
10621 card = items[ itemIndex ];
10623 card = this.stackLayout.getCurrentItem();
10627 this.selectFirstSelectableCard();
10628 card = this.stackLayout.getCurrentItem();
10633 // Only change the focus if is not already in the current page
10634 if ( !OO.ui.contains( card.$element[ 0 ], this.getElementDocument().activeElement, true ) ) {
10640 * Find the first focusable input in the index layout and focus
10643 OO.ui.IndexLayout.prototype.focusFirstFocusable = function () {
10644 OO.ui.findFocusable( this.stackLayout.$element ).focus();
10648 * Handle tab widget select events.
10651 * @param {OO.ui.OptionWidget|null} item Selected item
10653 OO.ui.IndexLayout.prototype.onTabSelectWidgetSelect = function ( item ) {
10655 this.setCard( item.getData() );
10660 * Get the card closest to the specified card.
10662 * @param {OO.ui.CardLayout} card Card to use as a reference point
10663 * @return {OO.ui.CardLayout|null} Card closest to the specified card
10665 OO.ui.IndexLayout.prototype.getClosestCard = function ( card ) {
10666 var next, prev, level,
10667 cards = this.stackLayout.getItems(),
10668 index = cards.indexOf( card );
10670 if ( index !== -1 ) {
10671 next = cards[ index + 1 ];
10672 prev = cards[ index - 1 ];
10673 // Prefer adjacent cards at the same level
10674 level = this.tabSelectWidget.getItemFromData( card.getName() ).getLevel();
10677 level === this.tabSelectWidget.getItemFromData( prev.getName() ).getLevel()
10683 level === this.tabSelectWidget.getItemFromData( next.getName() ).getLevel()
10688 return prev || next || null;
10692 * Get the tabs widget.
10694 * @return {OO.ui.TabSelectWidget} Tabs widget
10696 OO.ui.IndexLayout.prototype.getTabs = function () {
10697 return this.tabSelectWidget;
10701 * Get a card by its symbolic name.
10703 * @param {string} name Symbolic name of card
10704 * @return {OO.ui.CardLayout|undefined} Card, if found
10706 OO.ui.IndexLayout.prototype.getCard = function ( name ) {
10707 return this.cards[ name ];
10711 * Get the current card.
10713 * @return {OO.ui.CardLayout|undefined} Current card, if found
10715 OO.ui.IndexLayout.prototype.getCurrentCard = function () {
10716 var name = this.getCurrentCardName();
10717 return name ? this.getCard( name ) : undefined;
10721 * Get the symbolic name of the current card.
10723 * @return {string|null} Symbolic name of the current card
10725 OO.ui.IndexLayout.prototype.getCurrentCardName = function () {
10726 return this.currentCardName;
10730 * Add cards to the index layout
10732 * When cards are added with the same names as existing cards, the existing cards will be
10733 * automatically removed before the new cards are added.
10735 * @param {OO.ui.CardLayout[]} cards Cards to add
10736 * @param {number} index Index of the insertion point
10740 OO.ui.IndexLayout.prototype.addCards = function ( cards, index ) {
10741 var i, len, name, card, item, currentIndex,
10742 stackLayoutCards = this.stackLayout.getItems(),
10746 // Remove cards with same names
10747 for ( i = 0, len = cards.length; i < len; i++ ) {
10749 name = card.getName();
10751 if ( Object.prototype.hasOwnProperty.call( this.cards, name ) ) {
10752 // Correct the insertion index
10753 currentIndex = stackLayoutCards.indexOf( this.cards[ name ] );
10754 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
10757 remove.push( this.cards[ name ] );
10760 if ( remove.length ) {
10761 this.removeCards( remove );
10765 for ( i = 0, len = cards.length; i < len; i++ ) {
10767 name = card.getName();
10768 this.cards[ card.getName() ] = card;
10769 item = new OO.ui.TabOptionWidget( { data: name } );
10770 card.setTabItem( item );
10771 items.push( item );
10774 if ( items.length ) {
10775 this.tabSelectWidget.addItems( items, index );
10776 this.selectFirstSelectableCard();
10778 this.stackLayout.addItems( cards, index );
10779 this.emit( 'add', cards, index );
10785 * Remove the specified cards from the index layout.
10787 * To remove all cards from the index, you may wish to use the #clearCards method instead.
10789 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
10793 OO.ui.IndexLayout.prototype.removeCards = function ( cards ) {
10794 var i, len, name, card,
10797 for ( i = 0, len = cards.length; i < len; i++ ) {
10799 name = card.getName();
10800 delete this.cards[ name ];
10801 items.push( this.tabSelectWidget.getItemFromData( name ) );
10802 card.setTabItem( null );
10804 if ( items.length ) {
10805 this.tabSelectWidget.removeItems( items );
10806 this.selectFirstSelectableCard();
10808 this.stackLayout.removeItems( cards );
10809 this.emit( 'remove', cards );
10815 * Clear all cards from the index layout.
10817 * To remove only a subset of cards from the index, use the #removeCards method.
10822 OO.ui.IndexLayout.prototype.clearCards = function () {
10824 cards = this.stackLayout.getItems();
10827 this.currentCardName = null;
10828 this.tabSelectWidget.clearItems();
10829 for ( i = 0, len = cards.length; i < len; i++ ) {
10830 cards[ i ].setTabItem( null );
10832 this.stackLayout.clearItems();
10834 this.emit( 'remove', cards );
10840 * Set the current card by symbolic name.
10843 * @param {string} name Symbolic name of card
10845 OO.ui.IndexLayout.prototype.setCard = function ( name ) {
10848 card = this.cards[ name ],
10849 previousCard = this.currentCardName && this.cards[ this.currentCardName ];
10851 if ( name !== this.currentCardName ) {
10852 selectedItem = this.tabSelectWidget.getSelectedItem();
10853 if ( selectedItem && selectedItem.getData() !== name ) {
10854 this.tabSelectWidget.selectItemByData( name );
10857 if ( previousCard ) {
10858 previousCard.setActive( false );
10859 // Blur anything focused if the next card doesn't have anything focusable.
10860 // This is not needed if the next card has something focusable (because once it is focused
10861 // this blur happens automatically). If the layout is non-continuous, this check is
10862 // meaningless because the next card is not visible yet and thus can't hold focus.
10865 this.stackLayout.continuous &&
10866 OO.ui.findFocusable( card.$element ).length !== 0
10868 $focused = previousCard.$element.find( ':focus' );
10869 if ( $focused.length ) {
10870 $focused[ 0 ].blur();
10874 this.currentCardName = name;
10875 card.setActive( true );
10876 this.stackLayout.setItem( card );
10877 if ( !this.stackLayout.continuous && previousCard ) {
10878 // This should not be necessary, since any inputs on the previous card should have been
10879 // blurred when it was hidden, but browsers are not very consistent about this.
10880 $focused = previousCard.$element.find( ':focus' );
10881 if ( $focused.length ) {
10882 $focused[ 0 ].blur();
10885 this.emit( 'set', card );
10891 * Select the first selectable card.
10895 OO.ui.IndexLayout.prototype.selectFirstSelectableCard = function () {
10896 if ( !this.tabSelectWidget.getSelectedItem() ) {
10897 this.tabSelectWidget.selectItem( this.tabSelectWidget.getFirstSelectableItem() );
10904 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10905 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10908 * // Example of a panel layout
10909 * var panel = new OO.ui.PanelLayout( {
10913 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10915 * $( 'body' ).append( panel.$element );
10918 * @extends OO.ui.Layout
10921 * @param {Object} [config] Configuration options
10922 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10923 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10924 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10925 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10927 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
10928 // Configuration initialization
10929 config = $.extend( {
10936 // Parent constructor
10937 OO.ui.PanelLayout.parent.call( this, config );
10940 this.$element.addClass( 'oo-ui-panelLayout' );
10941 if ( config.scrollable ) {
10942 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
10944 if ( config.padded ) {
10945 this.$element.addClass( 'oo-ui-panelLayout-padded' );
10947 if ( config.expanded ) {
10948 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
10950 if ( config.framed ) {
10951 this.$element.addClass( 'oo-ui-panelLayout-framed' );
10957 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
10962 * Focus the panel layout
10964 * The default implementation just focuses the first focusable element in the panel
10966 OO.ui.PanelLayout.prototype.focus = function () {
10967 OO.ui.findFocusable( this.$element ).focus();
10971 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
10972 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
10973 * rather extended to include the required content and functionality.
10975 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
10976 * item is customized (with a label) using the #setupTabItem method. See
10977 * {@link OO.ui.IndexLayout IndexLayout} for an example.
10980 * @extends OO.ui.PanelLayout
10983 * @param {string} name Unique symbolic name of card
10984 * @param {Object} [config] Configuration options
10985 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] Label for card's tab
10987 OO.ui.CardLayout = function OoUiCardLayout( name, config ) {
10988 // Allow passing positional parameters inside the config object
10989 if ( OO.isPlainObject( name ) && config === undefined ) {
10991 name = config.name;
10994 // Configuration initialization
10995 config = $.extend( { scrollable: true }, config );
10997 // Parent constructor
10998 OO.ui.CardLayout.parent.call( this, config );
11002 this.label = config.label;
11003 this.tabItem = null;
11004 this.active = false;
11007 this.$element.addClass( 'oo-ui-cardLayout' );
11012 OO.inheritClass( OO.ui.CardLayout, OO.ui.PanelLayout );
11017 * An 'active' event is emitted when the card becomes active. Cards become active when they are
11018 * shown in a index layout that is configured to display only one card at a time.
11021 * @param {boolean} active Card is active
11027 * Get the symbolic name of the card.
11029 * @return {string} Symbolic name of card
11031 OO.ui.CardLayout.prototype.getName = function () {
11036 * Check if card is active.
11038 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
11039 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
11041 * @return {boolean} Card is active
11043 OO.ui.CardLayout.prototype.isActive = function () {
11044 return this.active;
11050 * The tab item allows users to access the card from the index's tab
11051 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
11053 * @return {OO.ui.TabOptionWidget|null} Tab option widget
11055 OO.ui.CardLayout.prototype.getTabItem = function () {
11056 return this.tabItem;
11060 * Set or unset the tab item.
11062 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
11063 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
11064 * level), use #setupTabItem instead of this method.
11066 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
11069 OO.ui.CardLayout.prototype.setTabItem = function ( tabItem ) {
11070 this.tabItem = tabItem || null;
11072 this.setupTabItem();
11078 * Set up the tab item.
11080 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
11081 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
11082 * the #setTabItem method instead.
11084 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
11087 OO.ui.CardLayout.prototype.setupTabItem = function () {
11088 if ( this.label ) {
11089 this.tabItem.setLabel( this.label );
11095 * Set the card to its 'active' state.
11097 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
11098 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
11099 * context, setting the active state on a card does nothing.
11101 * @param {boolean} value Card is active
11104 OO.ui.CardLayout.prototype.setActive = function ( active ) {
11107 if ( active !== this.active ) {
11108 this.active = active;
11109 this.$element.toggleClass( 'oo-ui-cardLayout-active', this.active );
11110 this.emit( 'active', this.active );
11115 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
11116 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
11117 * rather extended to include the required content and functionality.
11119 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
11120 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
11121 * {@link OO.ui.BookletLayout BookletLayout} for an example.
11124 * @extends OO.ui.PanelLayout
11127 * @param {string} name Unique symbolic name of page
11128 * @param {Object} [config] Configuration options
11130 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
11131 // Allow passing positional parameters inside the config object
11132 if ( OO.isPlainObject( name ) && config === undefined ) {
11134 name = config.name;
11137 // Configuration initialization
11138 config = $.extend( { scrollable: true }, config );
11140 // Parent constructor
11141 OO.ui.PageLayout.parent.call( this, config );
11145 this.outlineItem = null;
11146 this.active = false;
11149 this.$element.addClass( 'oo-ui-pageLayout' );
11154 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
11159 * An 'active' event is emitted when the page becomes active. Pages become active when they are
11160 * shown in a booklet layout that is configured to display only one page at a time.
11163 * @param {boolean} active Page is active
11169 * Get the symbolic name of the page.
11171 * @return {string} Symbolic name of page
11173 OO.ui.PageLayout.prototype.getName = function () {
11178 * Check if page is active.
11180 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
11181 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
11183 * @return {boolean} Page is active
11185 OO.ui.PageLayout.prototype.isActive = function () {
11186 return this.active;
11190 * Get outline item.
11192 * The outline item allows users to access the page from the booklet's outline
11193 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
11195 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
11197 OO.ui.PageLayout.prototype.getOutlineItem = function () {
11198 return this.outlineItem;
11202 * Set or unset the outline item.
11204 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
11205 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
11206 * level), use #setupOutlineItem instead of this method.
11208 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
11211 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
11212 this.outlineItem = outlineItem || null;
11213 if ( outlineItem ) {
11214 this.setupOutlineItem();
11220 * Set up the outline item.
11222 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
11223 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
11224 * the #setOutlineItem method instead.
11226 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
11229 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
11234 * Set the page to its 'active' state.
11236 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
11237 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
11238 * context, setting the active state on a page does nothing.
11240 * @param {boolean} value Page is active
11243 OO.ui.PageLayout.prototype.setActive = function ( active ) {
11246 if ( active !== this.active ) {
11247 this.active = active;
11248 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
11249 this.emit( 'active', this.active );
11254 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
11255 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
11256 * by setting the #continuous option to 'true'.
11259 * // A stack layout with two panels, configured to be displayed continously
11260 * var myStack = new OO.ui.StackLayout( {
11262 * new OO.ui.PanelLayout( {
11263 * $content: $( '<p>Panel One</p>' ),
11267 * new OO.ui.PanelLayout( {
11268 * $content: $( '<p>Panel Two</p>' ),
11275 * $( 'body' ).append( myStack.$element );
11278 * @extends OO.ui.PanelLayout
11279 * @mixins OO.ui.mixin.GroupElement
11282 * @param {Object} [config] Configuration options
11283 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
11284 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
11286 OO.ui.StackLayout = function OoUiStackLayout( config ) {
11287 // Configuration initialization
11288 config = $.extend( { scrollable: true }, config );
11290 // Parent constructor
11291 OO.ui.StackLayout.parent.call( this, config );
11293 // Mixin constructors
11294 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
11297 this.currentItem = null;
11298 this.continuous = !!config.continuous;
11301 this.$element.addClass( 'oo-ui-stackLayout' );
11302 if ( this.continuous ) {
11303 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
11304 this.$element.on( 'scroll', OO.ui.debounce( this.onScroll.bind( this ), 250 ) );
11306 if ( Array.isArray( config.items ) ) {
11307 this.addItems( config.items );
11313 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
11314 OO.mixinClass( OO.ui.StackLayout, OO.ui.mixin.GroupElement );
11319 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
11320 * {@link #clearItems cleared} or {@link #setItem displayed}.
11323 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
11327 * When used in continuous mode, this event is emitted when the user scrolls down
11328 * far enough such that currentItem is no longer visible.
11330 * @event visibleItemChange
11331 * @param {OO.ui.PanelLayout} panel The next visible item in the layout
11337 * Handle scroll events from the layout element
11339 * @param {jQuery.Event} e
11340 * @fires visibleItemChange
11342 OO.ui.StackLayout.prototype.onScroll = function () {
11344 len = this.items.length,
11345 currentIndex = this.items.indexOf( this.currentItem ),
11346 newIndex = currentIndex,
11347 containerRect = this.$element[ 0 ].getBoundingClientRect();
11349 if ( !containerRect || ( !containerRect.top && !containerRect.bottom ) ) {
11350 // Can't get bounding rect, possibly not attached.
11354 function getRect( item ) {
11355 return item.$element[ 0 ].getBoundingClientRect();
11358 function isVisible( item ) {
11359 var rect = getRect( item );
11360 return rect.bottom > containerRect.top && rect.top < containerRect.bottom;
11363 currentRect = getRect( this.currentItem );
11365 if ( currentRect.bottom < containerRect.top ) {
11366 // Scrolled down past current item
11367 while ( ++newIndex < len ) {
11368 if ( isVisible( this.items[ newIndex ] ) ) {
11372 } else if ( currentRect.top > containerRect.bottom ) {
11373 // Scrolled up past current item
11374 while ( --newIndex >= 0 ) {
11375 if ( isVisible( this.items[ newIndex ] ) ) {
11381 if ( newIndex !== currentIndex ) {
11382 this.emit( 'visibleItemChange', this.items[ newIndex ] );
11387 * Get the current panel.
11389 * @return {OO.ui.Layout|null}
11391 OO.ui.StackLayout.prototype.getCurrentItem = function () {
11392 return this.currentItem;
11396 * Unset the current item.
11399 * @param {OO.ui.StackLayout} layout
11402 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
11403 var prevItem = this.currentItem;
11404 if ( prevItem === null ) {
11408 this.currentItem = null;
11409 this.emit( 'set', null );
11413 * Add panel layouts to the stack layout.
11415 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
11416 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
11419 * @param {OO.ui.Layout[]} items Panels to add
11420 * @param {number} [index] Index of the insertion point
11423 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
11424 // Update the visibility
11425 this.updateHiddenState( items, this.currentItem );
11428 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items, index );
11430 if ( !this.currentItem && items.length ) {
11431 this.setItem( items[ 0 ] );
11438 * Remove the specified panels from the stack layout.
11440 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
11441 * you may wish to use the #clearItems method instead.
11443 * @param {OO.ui.Layout[]} items Panels to remove
11447 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
11449 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
11451 if ( items.indexOf( this.currentItem ) !== -1 ) {
11452 if ( this.items.length ) {
11453 this.setItem( this.items[ 0 ] );
11455 this.unsetCurrentItem();
11463 * Clear all panels from the stack layout.
11465 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
11466 * a subset of panels, use the #removeItems method.
11471 OO.ui.StackLayout.prototype.clearItems = function () {
11472 this.unsetCurrentItem();
11473 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
11479 * Show the specified panel.
11481 * If another panel is currently displayed, it will be hidden.
11483 * @param {OO.ui.Layout} item Panel to show
11487 OO.ui.StackLayout.prototype.setItem = function ( item ) {
11488 if ( item !== this.currentItem ) {
11489 this.updateHiddenState( this.items, item );
11491 if ( this.items.indexOf( item ) !== -1 ) {
11492 this.currentItem = item;
11493 this.emit( 'set', item );
11495 this.unsetCurrentItem();
11503 * Update the visibility of all items in case of non-continuous view.
11505 * Ensure all items are hidden except for the selected one.
11506 * This method does nothing when the stack is continuous.
11509 * @param {OO.ui.Layout[]} items Item list iterate over
11510 * @param {OO.ui.Layout} [selectedItem] Selected item to show
11512 OO.ui.StackLayout.prototype.updateHiddenState = function ( items, selectedItem ) {
11515 if ( !this.continuous ) {
11516 for ( i = 0, len = items.length; i < len; i++ ) {
11517 if ( !selectedItem || selectedItem !== items[ i ] ) {
11518 items[ i ].$element.addClass( 'oo-ui-element-hidden' );
11521 if ( selectedItem ) {
11522 selectedItem.$element.removeClass( 'oo-ui-element-hidden' );
11528 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
11529 * items), with small margins between them. Convenient when you need to put a number of block-level
11530 * widgets on a single line next to each other.
11532 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
11535 * // HorizontalLayout with a text input and a label
11536 * var layout = new OO.ui.HorizontalLayout( {
11538 * new OO.ui.LabelWidget( { label: 'Label' } ),
11539 * new OO.ui.TextInputWidget( { value: 'Text' } )
11542 * $( 'body' ).append( layout.$element );
11545 * @extends OO.ui.Layout
11546 * @mixins OO.ui.mixin.GroupElement
11549 * @param {Object} [config] Configuration options
11550 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
11552 OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) {
11553 // Configuration initialization
11554 config = config || {};
11556 // Parent constructor
11557 OO.ui.HorizontalLayout.parent.call( this, config );
11559 // Mixin constructors
11560 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
11563 this.$element.addClass( 'oo-ui-horizontalLayout' );
11564 if ( Array.isArray( config.items ) ) {
11565 this.addItems( config.items );
11571 OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout );
11572 OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement );
11575 * BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11576 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11577 * and {@link OO.ui.ListToolGroup ListToolGroup}). The {@link OO.ui.Tool tools} in a BarToolGroup are
11578 * displayed by icon in a single row. The title of the tool is displayed when users move the mouse over
11581 * BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar is
11585 * // Example of a BarToolGroup with two tools
11586 * var toolFactory = new OO.ui.ToolFactory();
11587 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11588 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11590 * // We will be placing status text in this element when tools are used
11591 * var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' );
11593 * // Define the tools that we're going to place in our toolbar
11595 * // Create a class inheriting from OO.ui.Tool
11596 * function SearchTool() {
11597 * SearchTool.parent.apply( this, arguments );
11599 * OO.inheritClass( SearchTool, OO.ui.Tool );
11600 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
11601 * // of 'icon' and 'title' (displayed icon and text).
11602 * SearchTool.static.name = 'search';
11603 * SearchTool.static.icon = 'search';
11604 * SearchTool.static.title = 'Search...';
11605 * // Defines the action that will happen when this tool is selected (clicked).
11606 * SearchTool.prototype.onSelect = function () {
11607 * $area.text( 'Search tool clicked!' );
11608 * // Never display this tool as "active" (selected).
11609 * this.setActive( false );
11611 * SearchTool.prototype.onUpdateState = function () {};
11612 * // Make this tool available in our toolFactory and thus our toolbar
11613 * toolFactory.register( SearchTool );
11615 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
11616 * // little popup window (a PopupWidget).
11617 * function HelpTool( toolGroup, config ) {
11618 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11623 * this.popup.$body.append( '<p>I am helpful!</p>' );
11625 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11626 * HelpTool.static.name = 'help';
11627 * HelpTool.static.icon = 'help';
11628 * HelpTool.static.title = 'Help';
11629 * toolFactory.register( HelpTool );
11631 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11632 * // used once (but not all defined tools must be used).
11635 * // 'bar' tool groups display tools by icon only
11637 * include: [ 'search', 'help' ]
11641 * // Create some UI around the toolbar and place it in the document
11642 * var frame = new OO.ui.PanelLayout( {
11646 * var contentFrame = new OO.ui.PanelLayout( {
11650 * frame.$element.append(
11651 * toolbar.$element,
11652 * contentFrame.$element.append( $area )
11654 * $( 'body' ).append( frame.$element );
11656 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11658 * toolbar.initialize();
11660 * For more information about how to add tools to a bar tool group, please see {@link OO.ui.ToolGroup toolgroup}.
11661 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11663 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11666 * @extends OO.ui.ToolGroup
11669 * @param {OO.ui.Toolbar} toolbar
11670 * @param {Object} [config] Configuration options
11672 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
11673 // Allow passing positional parameters inside the config object
11674 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11676 toolbar = config.toolbar;
11679 // Parent constructor
11680 OO.ui.BarToolGroup.parent.call( this, toolbar, config );
11683 this.$element.addClass( 'oo-ui-barToolGroup' );
11688 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
11690 /* Static Properties */
11692 OO.ui.BarToolGroup.static.titleTooltips = true;
11694 OO.ui.BarToolGroup.static.accelTooltips = true;
11696 OO.ui.BarToolGroup.static.name = 'bar';
11699 * PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup}
11700 * and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup--an overlaid menu or list of tools with an
11701 * optional icon and label. This class can be used for other base classes that also use this functionality.
11705 * @extends OO.ui.ToolGroup
11706 * @mixins OO.ui.mixin.IconElement
11707 * @mixins OO.ui.mixin.IndicatorElement
11708 * @mixins OO.ui.mixin.LabelElement
11709 * @mixins OO.ui.mixin.TitledElement
11710 * @mixins OO.ui.mixin.ClippableElement
11711 * @mixins OO.ui.mixin.TabIndexedElement
11714 * @param {OO.ui.Toolbar} toolbar
11715 * @param {Object} [config] Configuration options
11716 * @cfg {string} [header] Text to display at the top of the popup
11718 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
11719 // Allow passing positional parameters inside the config object
11720 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11722 toolbar = config.toolbar;
11725 // Configuration initialization
11726 config = config || {};
11728 // Parent constructor
11729 OO.ui.PopupToolGroup.parent.call( this, toolbar, config );
11732 this.active = false;
11733 this.dragging = false;
11734 this.onBlurHandler = this.onBlur.bind( this );
11735 this.$handle = $( '<span>' );
11737 // Mixin constructors
11738 OO.ui.mixin.IconElement.call( this, config );
11739 OO.ui.mixin.IndicatorElement.call( this, config );
11740 OO.ui.mixin.LabelElement.call( this, config );
11741 OO.ui.mixin.TitledElement.call( this, config );
11742 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
11743 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
11747 keydown: this.onHandleMouseKeyDown.bind( this ),
11748 keyup: this.onHandleMouseKeyUp.bind( this ),
11749 mousedown: this.onHandleMouseKeyDown.bind( this ),
11750 mouseup: this.onHandleMouseKeyUp.bind( this )
11755 .addClass( 'oo-ui-popupToolGroup-handle' )
11756 .append( this.$icon, this.$label, this.$indicator );
11757 // If the pop-up should have a header, add it to the top of the toolGroup.
11758 // Note: If this feature is useful for other widgets, we could abstract it into an
11759 // OO.ui.HeaderedElement mixin constructor.
11760 if ( config.header !== undefined ) {
11762 .prepend( $( '<span>' )
11763 .addClass( 'oo-ui-popupToolGroup-header' )
11764 .text( config.header )
11768 .addClass( 'oo-ui-popupToolGroup' )
11769 .prepend( this.$handle );
11774 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
11775 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IconElement );
11776 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IndicatorElement );
11777 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.LabelElement );
11778 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TitledElement );
11779 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.ClippableElement );
11780 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TabIndexedElement );
11787 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
11789 OO.ui.PopupToolGroup.parent.prototype.setDisabled.apply( this, arguments );
11791 if ( this.isDisabled() && this.isElementAttached() ) {
11792 this.setActive( false );
11797 * Handle focus being lost.
11799 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
11802 * @param {jQuery.Event} e Mouse up or key up event
11804 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
11805 // Only deactivate when clicking outside the dropdown element
11806 if ( $( e.target ).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element[ 0 ] ) {
11807 this.setActive( false );
11814 OO.ui.PopupToolGroup.prototype.onMouseKeyUp = function ( e ) {
11815 // Only close toolgroup when a tool was actually selected
11817 !this.isDisabled() && this.pressed && this.pressed === this.getTargetTool( e ) &&
11818 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11820 this.setActive( false );
11822 return OO.ui.PopupToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
11826 * Handle mouse up and key up events.
11829 * @param {jQuery.Event} e Mouse up or key up event
11831 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyUp = function ( e ) {
11833 !this.isDisabled() &&
11834 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11841 * Handle mouse down and key down events.
11844 * @param {jQuery.Event} e Mouse down or key down event
11846 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyDown = function ( e ) {
11848 !this.isDisabled() &&
11849 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11851 this.setActive( !this.active );
11857 * Switch into 'active' mode.
11859 * When active, the popup is visible. A mouseup event anywhere in the document will trigger
11862 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
11863 var containerWidth, containerLeft;
11865 if ( this.active !== value ) {
11866 this.active = value;
11868 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler );
11869 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler );
11871 this.$clippable.css( 'left', '' );
11872 // Try anchoring the popup to the left first
11873 this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
11874 this.toggleClipping( true );
11875 if ( this.isClippedHorizontally() ) {
11876 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
11877 this.toggleClipping( false );
11879 .removeClass( 'oo-ui-popupToolGroup-left' )
11880 .addClass( 'oo-ui-popupToolGroup-right' );
11881 this.toggleClipping( true );
11883 if ( this.isClippedHorizontally() ) {
11884 // Anchoring to the right also caused the popup to clip, so just make it fill the container
11885 containerWidth = this.$clippableScrollableContainer.width();
11886 containerLeft = this.$clippableScrollableContainer.offset().left;
11888 this.toggleClipping( false );
11889 this.$element.removeClass( 'oo-ui-popupToolGroup-right' );
11891 this.$clippable.css( {
11892 left: -( this.$element.offset().left - containerLeft ),
11893 width: containerWidth
11897 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler );
11898 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler );
11899 this.$element.removeClass(
11900 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
11902 this.toggleClipping( false );
11908 * ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11909 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11910 * and {@link OO.ui.BarToolGroup BarToolGroup}). The {@link OO.ui.Tool tools} in a ListToolGroup are displayed
11911 * by label in a dropdown menu. The title of the tool is used as the label text. The menu itself can be configured
11912 * with a label, icon, indicator, header, and title.
11914 * ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a ‘More’ option that
11915 * users can select to see the full list of tools. If a collapsed toolgroup is expanded, a ‘Fewer’ option permits
11916 * users to collapse the list again.
11918 * ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the toolbar is set up. The factory
11919 * requires the ListToolGroup's symbolic name, 'list', which is specified along with the other configurations. For more
11920 * information about how to add tools to a ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11923 * // Example of a ListToolGroup
11924 * var toolFactory = new OO.ui.ToolFactory();
11925 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11926 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11928 * // Configure and register two tools
11929 * function SettingsTool() {
11930 * SettingsTool.parent.apply( this, arguments );
11932 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11933 * SettingsTool.static.name = 'settings';
11934 * SettingsTool.static.icon = 'settings';
11935 * SettingsTool.static.title = 'Change settings';
11936 * SettingsTool.prototype.onSelect = function () {
11937 * this.setActive( false );
11939 * SettingsTool.prototype.onUpdateState = function () {};
11940 * toolFactory.register( SettingsTool );
11941 * // Register two more tools, nothing interesting here
11942 * function StuffTool() {
11943 * StuffTool.parent.apply( this, arguments );
11945 * OO.inheritClass( StuffTool, OO.ui.Tool );
11946 * StuffTool.static.name = 'stuff';
11947 * StuffTool.static.icon = 'search';
11948 * StuffTool.static.title = 'Change the world';
11949 * StuffTool.prototype.onSelect = function () {
11950 * this.setActive( false );
11952 * StuffTool.prototype.onUpdateState = function () {};
11953 * toolFactory.register( StuffTool );
11956 * // Configurations for list toolgroup.
11958 * label: 'ListToolGroup',
11959 * indicator: 'down',
11960 * icon: 'ellipsis',
11961 * title: 'This is the title, displayed when user moves the mouse over the list toolgroup',
11962 * header: 'This is the header',
11963 * include: [ 'settings', 'stuff' ],
11964 * allowCollapse: ['stuff']
11968 * // Create some UI around the toolbar and place it in the document
11969 * var frame = new OO.ui.PanelLayout( {
11973 * frame.$element.append(
11976 * $( 'body' ).append( frame.$element );
11977 * // Build the toolbar. This must be done after the toolbar has been appended to the document.
11978 * toolbar.initialize();
11980 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11982 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11985 * @extends OO.ui.PopupToolGroup
11988 * @param {OO.ui.Toolbar} toolbar
11989 * @param {Object} [config] Configuration options
11990 * @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible tools
11991 * will only be displayed if users click the ‘More’ option displayed at the bottom of the list. If
11992 * the list is expanded, a ‘Fewer’ option permits users to collapse the list again. Any tools that
11993 * are included in the toolgroup, but are not designated as collapsible, will always be displayed.
11994 * To open a collapsible list in its expanded state, set #expanded to 'true'.
11995 * @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as collapsible.
11996 * Unless #expanded is set to true, the collapsible tools will be collapsed when the list is first opened.
11997 * @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools have
11998 * been designated as collapsible. When expanded is set to true, all tools in the group will be displayed
11999 * when the list is first opened. Users can collapse the list with a ‘Fewer’ option at the bottom.
12001 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
12002 // Allow passing positional parameters inside the config object
12003 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
12005 toolbar = config.toolbar;
12008 // Configuration initialization
12009 config = config || {};
12011 // Properties (must be set before parent constructor, which calls #populate)
12012 this.allowCollapse = config.allowCollapse;
12013 this.forceExpand = config.forceExpand;
12014 this.expanded = config.expanded !== undefined ? config.expanded : false;
12015 this.collapsibleTools = [];
12017 // Parent constructor
12018 OO.ui.ListToolGroup.parent.call( this, toolbar, config );
12021 this.$element.addClass( 'oo-ui-listToolGroup' );
12026 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
12028 /* Static Properties */
12030 OO.ui.ListToolGroup.static.name = 'list';
12037 OO.ui.ListToolGroup.prototype.populate = function () {
12038 var i, len, allowCollapse = [];
12040 OO.ui.ListToolGroup.parent.prototype.populate.call( this );
12042 // Update the list of collapsible tools
12043 if ( this.allowCollapse !== undefined ) {
12044 allowCollapse = this.allowCollapse;
12045 } else if ( this.forceExpand !== undefined ) {
12046 allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand );
12049 this.collapsibleTools = [];
12050 for ( i = 0, len = allowCollapse.length; i < len; i++ ) {
12051 if ( this.tools[ allowCollapse[ i ] ] !== undefined ) {
12052 this.collapsibleTools.push( this.tools[ allowCollapse[ i ] ] );
12056 // Keep at the end, even when tools are added
12057 this.$group.append( this.getExpandCollapseTool().$element );
12059 this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 );
12060 this.updateCollapsibleState();
12063 OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () {
12064 var ExpandCollapseTool;
12065 if ( this.expandCollapseTool === undefined ) {
12066 ExpandCollapseTool = function () {
12067 ExpandCollapseTool.parent.apply( this, arguments );
12070 OO.inheritClass( ExpandCollapseTool, OO.ui.Tool );
12072 ExpandCollapseTool.prototype.onSelect = function () {
12073 this.toolGroup.expanded = !this.toolGroup.expanded;
12074 this.toolGroup.updateCollapsibleState();
12075 this.setActive( false );
12077 ExpandCollapseTool.prototype.onUpdateState = function () {
12078 // Do nothing. Tool interface requires an implementation of this function.
12081 ExpandCollapseTool.static.name = 'more-fewer';
12083 this.expandCollapseTool = new ExpandCollapseTool( this );
12085 return this.expandCollapseTool;
12091 OO.ui.ListToolGroup.prototype.onMouseKeyUp = function ( e ) {
12092 // Do not close the popup when the user wants to show more/fewer tools
12094 $( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length &&
12095 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
12097 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
12098 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
12099 return OO.ui.ListToolGroup.parent.parent.prototype.onMouseKeyUp.call( this, e );
12101 return OO.ui.ListToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
12105 OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () {
12108 this.getExpandCollapseTool()
12109 .setIcon( this.expanded ? 'collapse' : 'expand' )
12110 .setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
12112 for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) {
12113 this.collapsibleTools[ i ].toggle( this.expanded );
12118 * MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
12119 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.BarToolGroup BarToolGroup}
12120 * and {@link OO.ui.ListToolGroup ListToolGroup}). MenuToolGroups contain selectable {@link OO.ui.Tool tools},
12121 * which are displayed by label in a dropdown menu. The tool's title is used as the label text, and the
12122 * menu label is updated to reflect which tool or tools are currently selected. If no tools are selected,
12123 * the menu label is empty. The menu can be configured with an indicator, icon, title, and/or header.
12125 * MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar
12129 * // Example of a MenuToolGroup
12130 * var toolFactory = new OO.ui.ToolFactory();
12131 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
12132 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
12134 * // We will be placing status text in this element when tools are used
12135 * var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the dropdown menu.' );
12137 * // Define the tools that we're going to place in our toolbar
12139 * function SettingsTool() {
12140 * SettingsTool.parent.apply( this, arguments );
12141 * this.reallyActive = false;
12143 * OO.inheritClass( SettingsTool, OO.ui.Tool );
12144 * SettingsTool.static.name = 'settings';
12145 * SettingsTool.static.icon = 'settings';
12146 * SettingsTool.static.title = 'Change settings';
12147 * SettingsTool.prototype.onSelect = function () {
12148 * $area.text( 'Settings tool clicked!' );
12149 * // Toggle the active state on each click
12150 * this.reallyActive = !this.reallyActive;
12151 * this.setActive( this.reallyActive );
12152 * // To update the menu label
12153 * this.toolbar.emit( 'updateState' );
12155 * SettingsTool.prototype.onUpdateState = function () {};
12156 * toolFactory.register( SettingsTool );
12158 * function StuffTool() {
12159 * StuffTool.parent.apply( this, arguments );
12160 * this.reallyActive = false;
12162 * OO.inheritClass( StuffTool, OO.ui.Tool );
12163 * StuffTool.static.name = 'stuff';
12164 * StuffTool.static.icon = 'ellipsis';
12165 * StuffTool.static.title = 'More stuff';
12166 * StuffTool.prototype.onSelect = function () {
12167 * $area.text( 'More stuff tool clicked!' );
12168 * // Toggle the active state on each click
12169 * this.reallyActive = !this.reallyActive;
12170 * this.setActive( this.reallyActive );
12171 * // To update the menu label
12172 * this.toolbar.emit( 'updateState' );
12174 * StuffTool.prototype.onUpdateState = function () {};
12175 * toolFactory.register( StuffTool );
12177 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
12178 * // used once (but not all defined tools must be used).
12182 * header: 'This is the (optional) header',
12183 * title: 'This is the (optional) title',
12184 * indicator: 'down',
12185 * include: [ 'settings', 'stuff' ]
12189 * // Create some UI around the toolbar and place it in the document
12190 * var frame = new OO.ui.PanelLayout( {
12194 * var contentFrame = new OO.ui.PanelLayout( {
12198 * frame.$element.append(
12199 * toolbar.$element,
12200 * contentFrame.$element.append( $area )
12202 * $( 'body' ).append( frame.$element );
12204 * // Here is where the toolbar is actually built. This must be done after inserting it into the
12206 * toolbar.initialize();
12207 * toolbar.emit( 'updateState' );
12209 * For more information about how to add tools to a MenuToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
12210 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki] [1].
12212 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
12215 * @extends OO.ui.PopupToolGroup
12218 * @param {OO.ui.Toolbar} toolbar
12219 * @param {Object} [config] Configuration options
12221 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
12222 // Allow passing positional parameters inside the config object
12223 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
12225 toolbar = config.toolbar;
12228 // Configuration initialization
12229 config = config || {};
12231 // Parent constructor
12232 OO.ui.MenuToolGroup.parent.call( this, toolbar, config );
12235 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
12238 this.$element.addClass( 'oo-ui-menuToolGroup' );
12243 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
12245 /* Static Properties */
12247 OO.ui.MenuToolGroup.static.name = 'menu';
12252 * Handle the toolbar state being updated.
12254 * When the state changes, the title of each active item in the menu will be joined together and
12255 * used as a label for the group. The label will be empty if none of the items are active.
12259 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
12263 for ( name in this.tools ) {
12264 if ( this.tools[ name ].isActive() ) {
12265 labelTexts.push( this.tools[ name ].getTitle() );
12269 this.setLabel( labelTexts.join( ', ' ) || ' ' );
12273 * Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. Each popup tool is configured
12274 * 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
12275 * an #onSelect or #onUpdateState method, as these methods have been implemented already.
12277 * // Example of a popup tool. When selected, a popup tool displays
12278 * // a popup window.
12279 * function HelpTool( toolGroup, config ) {
12280 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
12285 * this.popup.$body.append( '<p>I am helpful!</p>' );
12287 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
12288 * HelpTool.static.name = 'help';
12289 * HelpTool.static.icon = 'help';
12290 * HelpTool.static.title = 'Help';
12291 * toolFactory.register( HelpTool );
12293 * For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. For more information about
12294 * toolbars in genreral, please see the [OOjs UI documentation on MediaWiki][1].
12296 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
12300 * @extends OO.ui.Tool
12301 * @mixins OO.ui.mixin.PopupElement
12304 * @param {OO.ui.ToolGroup} toolGroup
12305 * @param {Object} [config] Configuration options
12307 OO.ui.PopupTool = function OoUiPopupTool( toolGroup, config ) {
12308 // Allow passing positional parameters inside the config object
12309 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
12310 config = toolGroup;
12311 toolGroup = config.toolGroup;
12314 // Parent constructor
12315 OO.ui.PopupTool.parent.call( this, toolGroup, config );
12317 // Mixin constructors
12318 OO.ui.mixin.PopupElement.call( this, config );
12322 .addClass( 'oo-ui-popupTool' )
12323 .append( this.popup.$element );
12328 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
12329 OO.mixinClass( OO.ui.PopupTool, OO.ui.mixin.PopupElement );
12334 * Handle the tool being selected.
12338 OO.ui.PopupTool.prototype.onSelect = function () {
12339 if ( !this.isDisabled() ) {
12340 this.popup.toggle();
12342 this.setActive( false );
12347 * Handle the toolbar state being updated.
12351 OO.ui.PopupTool.prototype.onUpdateState = function () {
12352 this.setActive( false );
12356 * A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools}
12357 * and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used
12358 * inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from
12359 * the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list}
12360 * when the ToolGroupTool is selected.
12362 * // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', defined elsewhere.
12364 * function SettingsTool() {
12365 * SettingsTool.parent.apply( this, arguments );
12367 * OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool );
12368 * SettingsTool.static.name = 'settings';
12369 * SettingsTool.static.title = 'Change settings';
12370 * SettingsTool.static.groupConfig = {
12371 * icon: 'settings',
12372 * label: 'ToolGroupTool',
12373 * include: [ 'setting1', 'setting2' ]
12375 * toolFactory.register( SettingsTool );
12377 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
12379 * Please note that this implementation is subject to change per [T74159] [2].
12381 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars#ToolGroupTool
12382 * [2]: https://phabricator.wikimedia.org/T74159
12386 * @extends OO.ui.Tool
12389 * @param {OO.ui.ToolGroup} toolGroup
12390 * @param {Object} [config] Configuration options
12392 OO.ui.ToolGroupTool = function OoUiToolGroupTool( toolGroup, config ) {
12393 // Allow passing positional parameters inside the config object
12394 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
12395 config = toolGroup;
12396 toolGroup = config.toolGroup;
12399 // Parent constructor
12400 OO.ui.ToolGroupTool.parent.call( this, toolGroup, config );
12403 this.innerToolGroup = this.createGroup( this.constructor.static.groupConfig );
12406 this.innerToolGroup.connect( this, { disable: 'onToolGroupDisable' } );
12409 this.$link.remove();
12411 .addClass( 'oo-ui-toolGroupTool' )
12412 .append( this.innerToolGroup.$element );
12417 OO.inheritClass( OO.ui.ToolGroupTool, OO.ui.Tool );
12419 /* Static Properties */
12422 * Toolgroup configuration.
12424 * The toolgroup configuration consists of the tools to include, as well as an icon and label
12425 * to use for the bar item. Tools can be included by symbolic name, group, or with the
12426 * wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information.
12428 * @property {Object.<string,Array>}
12430 OO.ui.ToolGroupTool.static.groupConfig = {};
12435 * Handle the tool being selected.
12439 OO.ui.ToolGroupTool.prototype.onSelect = function () {
12440 this.innerToolGroup.setActive( !this.innerToolGroup.active );
12445 * Synchronize disabledness state of the tool with the inner toolgroup.
12448 * @param {boolean} disabled Element is disabled
12450 OO.ui.ToolGroupTool.prototype.onToolGroupDisable = function ( disabled ) {
12451 this.setDisabled( disabled );
12455 * Handle the toolbar state being updated.
12459 OO.ui.ToolGroupTool.prototype.onUpdateState = function () {
12460 this.setActive( false );
12464 * Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration.
12466 * @param {Object.<string,Array>} group Toolgroup configuration. Please see {@link OO.ui.ToolGroup toolgroup} for
12467 * more information.
12468 * @return {OO.ui.ListToolGroup}
12470 OO.ui.ToolGroupTool.prototype.createGroup = function ( group ) {
12471 if ( group.include === '*' ) {
12472 // Apply defaults to catch-all groups
12473 if ( group.label === undefined ) {
12474 group.label = OO.ui.msg( 'ooui-toolbar-more' );
12478 return this.toolbar.getToolGroupFactory().create( 'list', this.toolbar, group );
12482 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
12484 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
12489 * @extends OO.ui.mixin.GroupElement
12492 * @param {Object} [config] Configuration options
12494 OO.ui.mixin.GroupWidget = function OoUiMixinGroupWidget( config ) {
12495 // Parent constructor
12496 OO.ui.mixin.GroupWidget.parent.call( this, config );
12501 OO.inheritClass( OO.ui.mixin.GroupWidget, OO.ui.mixin.GroupElement );
12506 * Set the disabled state of the widget.
12508 * This will also update the disabled state of child widgets.
12510 * @param {boolean} disabled Disable widget
12513 OO.ui.mixin.GroupWidget.prototype.setDisabled = function ( disabled ) {
12517 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
12518 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
12520 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
12521 if ( this.items ) {
12522 for ( i = 0, len = this.items.length; i < len; i++ ) {
12523 this.items[ i ].updateDisabled();
12531 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
12533 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
12534 * allows bidirectional communication.
12536 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
12544 OO.ui.mixin.ItemWidget = function OoUiMixinItemWidget() {
12551 * Check if widget is disabled.
12553 * Checks parent if present, making disabled state inheritable.
12555 * @return {boolean} Widget is disabled
12557 OO.ui.mixin.ItemWidget.prototype.isDisabled = function () {
12558 return this.disabled ||
12559 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
12563 * Set group element is in.
12565 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
12568 OO.ui.mixin.ItemWidget.prototype.setElementGroup = function ( group ) {
12570 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
12571 OO.ui.Element.prototype.setElementGroup.call( this, group );
12573 // Initialize item disabled states
12574 this.updateDisabled();
12580 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
12581 * Controls include moving items up and down, removing items, and adding different kinds of items.
12583 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
12586 * @extends OO.ui.Widget
12587 * @mixins OO.ui.mixin.GroupElement
12588 * @mixins OO.ui.mixin.IconElement
12591 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
12592 * @param {Object} [config] Configuration options
12593 * @cfg {Object} [abilities] List of abilties
12594 * @cfg {boolean} [abilities.move=true] Allow moving movable items
12595 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
12597 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
12598 // Allow passing positional parameters inside the config object
12599 if ( OO.isPlainObject( outline ) && config === undefined ) {
12601 outline = config.outline;
12604 // Configuration initialization
12605 config = $.extend( { icon: 'add' }, config );
12607 // Parent constructor
12608 OO.ui.OutlineControlsWidget.parent.call( this, config );
12610 // Mixin constructors
12611 OO.ui.mixin.GroupElement.call( this, config );
12612 OO.ui.mixin.IconElement.call( this, config );
12615 this.outline = outline;
12616 this.$movers = $( '<div>' );
12617 this.upButton = new OO.ui.ButtonWidget( {
12620 title: OO.ui.msg( 'ooui-outline-control-move-up' )
12622 this.downButton = new OO.ui.ButtonWidget( {
12625 title: OO.ui.msg( 'ooui-outline-control-move-down' )
12627 this.removeButton = new OO.ui.ButtonWidget( {
12630 title: OO.ui.msg( 'ooui-outline-control-remove' )
12632 this.abilities = { move: true, remove: true };
12635 outline.connect( this, {
12636 select: 'onOutlineChange',
12637 add: 'onOutlineChange',
12638 remove: 'onOutlineChange'
12640 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
12641 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
12642 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
12645 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
12646 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
12648 .addClass( 'oo-ui-outlineControlsWidget-movers' )
12649 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
12650 this.$element.append( this.$icon, this.$group, this.$movers );
12651 this.setAbilities( config.abilities || {} );
12656 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
12657 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.GroupElement );
12658 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.IconElement );
12664 * @param {number} places Number of places to move
12676 * @param {Object} abilities List of abilties
12677 * @param {boolean} [abilities.move] Allow moving movable items
12678 * @param {boolean} [abilities.remove] Allow removing removable items
12680 OO.ui.OutlineControlsWidget.prototype.setAbilities = function ( abilities ) {
12683 for ( ability in this.abilities ) {
12684 if ( abilities[ ability ] !== undefined ) {
12685 this.abilities[ ability ] = !!abilities[ ability ];
12689 this.onOutlineChange();
12694 * Handle outline change events.
12696 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
12697 var i, len, firstMovable, lastMovable,
12698 items = this.outline.getItems(),
12699 selectedItem = this.outline.getSelectedItem(),
12700 movable = this.abilities.move && selectedItem && selectedItem.isMovable(),
12701 removable = this.abilities.remove && selectedItem && selectedItem.isRemovable();
12705 len = items.length;
12706 while ( ++i < len ) {
12707 if ( items[ i ].isMovable() ) {
12708 firstMovable = items[ i ];
12714 if ( items[ i ].isMovable() ) {
12715 lastMovable = items[ i ];
12720 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
12721 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
12722 this.removeButton.setDisabled( !removable );
12726 * ToggleWidget implements basic behavior of widgets with an on/off state.
12727 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
12731 * @extends OO.ui.Widget
12734 * @param {Object} [config] Configuration options
12735 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
12736 * By default, the toggle is in the 'off' state.
12738 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
12739 // Configuration initialization
12740 config = config || {};
12742 // Parent constructor
12743 OO.ui.ToggleWidget.parent.call( this, config );
12749 this.$element.addClass( 'oo-ui-toggleWidget' );
12750 this.setValue( !!config.value );
12755 OO.inheritClass( OO.ui.ToggleWidget, OO.ui.Widget );
12762 * A change event is emitted when the on/off state of the toggle changes.
12764 * @param {boolean} value Value representing the new state of the toggle
12770 * Get the value representing the toggle’s state.
12772 * @return {boolean} The on/off state of the toggle
12774 OO.ui.ToggleWidget.prototype.getValue = function () {
12779 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
12781 * @param {boolean} value The state of the toggle
12785 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
12787 if ( this.value !== value ) {
12788 this.value = value;
12789 this.emit( 'change', value );
12790 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
12791 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
12792 this.$element.attr( 'aria-checked', value.toString() );
12798 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
12799 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
12800 * removed, and cleared from the group.
12803 * // Example: A ButtonGroupWidget with two buttons
12804 * var button1 = new OO.ui.PopupButtonWidget( {
12805 * label: 'Select a category',
12808 * $content: $( '<p>List of categories...</p>' ),
12813 * var button2 = new OO.ui.ButtonWidget( {
12814 * label: 'Add item'
12816 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
12817 * items: [button1, button2]
12819 * $( 'body' ).append( buttonGroup.$element );
12822 * @extends OO.ui.Widget
12823 * @mixins OO.ui.mixin.GroupElement
12826 * @param {Object} [config] Configuration options
12827 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
12829 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
12830 // Configuration initialization
12831 config = config || {};
12833 // Parent constructor
12834 OO.ui.ButtonGroupWidget.parent.call( this, config );
12836 // Mixin constructors
12837 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
12840 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
12841 if ( Array.isArray( config.items ) ) {
12842 this.addItems( config.items );
12848 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
12849 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.GroupElement );
12852 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
12853 * feels, and functionality can be customized via the class’s configuration options
12854 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12857 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
12860 * // A button widget
12861 * var button = new OO.ui.ButtonWidget( {
12862 * label: 'Button with Icon',
12864 * iconTitle: 'Remove'
12866 * $( 'body' ).append( button.$element );
12868 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
12871 * @extends OO.ui.Widget
12872 * @mixins OO.ui.mixin.ButtonElement
12873 * @mixins OO.ui.mixin.IconElement
12874 * @mixins OO.ui.mixin.IndicatorElement
12875 * @mixins OO.ui.mixin.LabelElement
12876 * @mixins OO.ui.mixin.TitledElement
12877 * @mixins OO.ui.mixin.FlaggedElement
12878 * @mixins OO.ui.mixin.TabIndexedElement
12879 * @mixins OO.ui.mixin.AccessKeyedElement
12882 * @param {Object} [config] Configuration options
12883 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
12884 * @cfg {string} [target] The frame or window in which to open the hyperlink.
12885 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
12887 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
12888 // Configuration initialization
12889 config = config || {};
12891 // Parent constructor
12892 OO.ui.ButtonWidget.parent.call( this, config );
12894 // Mixin constructors
12895 OO.ui.mixin.ButtonElement.call( this, config );
12896 OO.ui.mixin.IconElement.call( this, config );
12897 OO.ui.mixin.IndicatorElement.call( this, config );
12898 OO.ui.mixin.LabelElement.call( this, config );
12899 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
12900 OO.ui.mixin.FlaggedElement.call( this, config );
12901 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
12902 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$button } ) );
12906 this.target = null;
12907 this.noFollow = false;
12910 this.connect( this, { disable: 'onDisable' } );
12913 this.$button.append( this.$icon, this.$label, this.$indicator );
12915 .addClass( 'oo-ui-buttonWidget' )
12916 .append( this.$button );
12917 this.setHref( config.href );
12918 this.setTarget( config.target );
12919 this.setNoFollow( config.noFollow );
12924 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
12925 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.ButtonElement );
12926 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IconElement );
12927 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IndicatorElement );
12928 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.LabelElement );
12929 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TitledElement );
12930 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.FlaggedElement );
12931 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TabIndexedElement );
12932 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.AccessKeyedElement );
12939 OO.ui.ButtonWidget.prototype.onMouseDown = function ( e ) {
12940 if ( !this.isDisabled() ) {
12941 // Remove the tab-index while the button is down to prevent the button from stealing focus
12942 this.$button.removeAttr( 'tabindex' );
12945 return OO.ui.mixin.ButtonElement.prototype.onMouseDown.call( this, e );
12951 OO.ui.ButtonWidget.prototype.onMouseUp = function ( e ) {
12952 if ( !this.isDisabled() ) {
12953 // Restore the tab-index after the button is up to restore the button's accessibility
12954 this.$button.attr( 'tabindex', this.tabIndex );
12957 return OO.ui.mixin.ButtonElement.prototype.onMouseUp.call( this, e );
12961 * Get hyperlink location.
12963 * @return {string} Hyperlink location
12965 OO.ui.ButtonWidget.prototype.getHref = function () {
12970 * Get hyperlink target.
12972 * @return {string} Hyperlink target
12974 OO.ui.ButtonWidget.prototype.getTarget = function () {
12975 return this.target;
12979 * Get search engine traversal hint.
12981 * @return {boolean} Whether search engines should avoid traversing this hyperlink
12983 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
12984 return this.noFollow;
12988 * Set hyperlink location.
12990 * @param {string|null} href Hyperlink location, null to remove
12992 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
12993 href = typeof href === 'string' ? href : null;
12994 if ( href !== null ) {
12995 if ( !OO.ui.isSafeUrl( href ) ) {
12996 throw new Error( 'Potentially unsafe href provided: ' + href );
13001 if ( href !== this.href ) {
13010 * Update the `href` attribute, in case of changes to href or
13016 OO.ui.ButtonWidget.prototype.updateHref = function () {
13017 if ( this.href !== null && !this.isDisabled() ) {
13018 this.$button.attr( 'href', this.href );
13020 this.$button.removeAttr( 'href' );
13027 * Handle disable events.
13030 * @param {boolean} disabled Element is disabled
13032 OO.ui.ButtonWidget.prototype.onDisable = function () {
13037 * Set hyperlink target.
13039 * @param {string|null} target Hyperlink target, null to remove
13041 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
13042 target = typeof target === 'string' ? target : null;
13044 if ( target !== this.target ) {
13045 this.target = target;
13046 if ( target !== null ) {
13047 this.$button.attr( 'target', target );
13049 this.$button.removeAttr( 'target' );
13057 * Set search engine traversal hint.
13059 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
13061 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
13062 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
13064 if ( noFollow !== this.noFollow ) {
13065 this.noFollow = noFollow;
13067 this.$button.attr( 'rel', 'nofollow' );
13069 this.$button.removeAttr( 'rel' );
13077 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
13078 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
13081 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
13082 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
13085 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
13088 * @extends OO.ui.ButtonWidget
13089 * @mixins OO.ui.mixin.PendingElement
13092 * @param {Object} [config] Configuration options
13093 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
13094 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
13095 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
13096 * for more information about setting modes.
13097 * @cfg {boolean} [framed=false] Render the action button with a frame
13099 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
13100 // Configuration initialization
13101 config = $.extend( { framed: false }, config );
13103 // Parent constructor
13104 OO.ui.ActionWidget.parent.call( this, config );
13106 // Mixin constructors
13107 OO.ui.mixin.PendingElement.call( this, config );
13110 this.action = config.action || '';
13111 this.modes = config.modes || [];
13116 this.$element.addClass( 'oo-ui-actionWidget' );
13121 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
13122 OO.mixinClass( OO.ui.ActionWidget, OO.ui.mixin.PendingElement );
13127 * A resize event is emitted when the size of the widget changes.
13135 * Check if the action is configured to be available in the specified `mode`.
13137 * @param {string} mode Name of mode
13138 * @return {boolean} The action is configured with the mode
13140 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
13141 return this.modes.indexOf( mode ) !== -1;
13145 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
13149 OO.ui.ActionWidget.prototype.getAction = function () {
13150 return this.action;
13154 * Get the symbolic name of the mode or modes for which the action is configured to be available.
13156 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
13157 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
13160 * @return {string[]}
13162 OO.ui.ActionWidget.prototype.getModes = function () {
13163 return this.modes.slice();
13167 * Emit a resize event if the size has changed.
13172 OO.ui.ActionWidget.prototype.propagateResize = function () {
13175 if ( this.isElementAttached() ) {
13176 width = this.$element.width();
13177 height = this.$element.height();
13179 if ( width !== this.width || height !== this.height ) {
13180 this.width = width;
13181 this.height = height;
13182 this.emit( 'resize' );
13192 OO.ui.ActionWidget.prototype.setIcon = function () {
13194 OO.ui.mixin.IconElement.prototype.setIcon.apply( this, arguments );
13195 this.propagateResize();
13203 OO.ui.ActionWidget.prototype.setLabel = function () {
13205 OO.ui.mixin.LabelElement.prototype.setLabel.apply( this, arguments );
13206 this.propagateResize();
13214 OO.ui.ActionWidget.prototype.setFlags = function () {
13216 OO.ui.mixin.FlaggedElement.prototype.setFlags.apply( this, arguments );
13217 this.propagateResize();
13225 OO.ui.ActionWidget.prototype.clearFlags = function () {
13227 OO.ui.mixin.FlaggedElement.prototype.clearFlags.apply( this, arguments );
13228 this.propagateResize();
13234 * Toggle the visibility of the action button.
13236 * @param {boolean} [show] Show button, omit to toggle visibility
13239 OO.ui.ActionWidget.prototype.toggle = function () {
13241 OO.ui.ActionWidget.parent.prototype.toggle.apply( this, arguments );
13242 this.propagateResize();
13248 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
13249 * which is used to display additional information or options.
13252 * // Example of a popup button.
13253 * var popupButton = new OO.ui.PopupButtonWidget( {
13254 * label: 'Popup button with options',
13257 * $content: $( '<p>Additional options here.</p>' ),
13259 * align: 'force-left'
13262 * // Append the button to the DOM.
13263 * $( 'body' ).append( popupButton.$element );
13266 * @extends OO.ui.ButtonWidget
13267 * @mixins OO.ui.mixin.PopupElement
13270 * @param {Object} [config] Configuration options
13272 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
13273 // Parent constructor
13274 OO.ui.PopupButtonWidget.parent.call( this, config );
13276 // Mixin constructors
13277 OO.ui.mixin.PopupElement.call( this, config );
13280 this.connect( this, { click: 'onAction' } );
13284 .addClass( 'oo-ui-popupButtonWidget' )
13285 .attr( 'aria-haspopup', 'true' )
13286 .append( this.popup.$element );
13291 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
13292 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.mixin.PopupElement );
13297 * Handle the button action being triggered.
13301 OO.ui.PopupButtonWidget.prototype.onAction = function () {
13302 this.popup.toggle();
13306 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
13307 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
13308 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
13309 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
13310 * and {@link OO.ui.mixin.LabelElement labels}. Please see
13311 * the [OOjs UI documentation][1] on MediaWiki for more information.
13314 * // Toggle buttons in the 'off' and 'on' state.
13315 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
13316 * label: 'Toggle Button off'
13318 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
13319 * label: 'Toggle Button on',
13322 * // Append the buttons to the DOM.
13323 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
13325 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
13328 * @extends OO.ui.ToggleWidget
13329 * @mixins OO.ui.mixin.ButtonElement
13330 * @mixins OO.ui.mixin.IconElement
13331 * @mixins OO.ui.mixin.IndicatorElement
13332 * @mixins OO.ui.mixin.LabelElement
13333 * @mixins OO.ui.mixin.TitledElement
13334 * @mixins OO.ui.mixin.FlaggedElement
13335 * @mixins OO.ui.mixin.TabIndexedElement
13338 * @param {Object} [config] Configuration options
13339 * @cfg {boolean} [value=false] The toggle button’s initial on/off
13340 * state. By default, the button is in the 'off' state.
13342 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
13343 // Configuration initialization
13344 config = config || {};
13346 // Parent constructor
13347 OO.ui.ToggleButtonWidget.parent.call( this, config );
13349 // Mixin constructors
13350 OO.ui.mixin.ButtonElement.call( this, config );
13351 OO.ui.mixin.IconElement.call( this, config );
13352 OO.ui.mixin.IndicatorElement.call( this, config );
13353 OO.ui.mixin.LabelElement.call( this, config );
13354 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
13355 OO.ui.mixin.FlaggedElement.call( this, config );
13356 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
13359 this.connect( this, { click: 'onAction' } );
13362 this.$button.append( this.$icon, this.$label, this.$indicator );
13364 .addClass( 'oo-ui-toggleButtonWidget' )
13365 .append( this.$button );
13370 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
13371 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.ButtonElement );
13372 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IconElement );
13373 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IndicatorElement );
13374 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.LabelElement );
13375 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TitledElement );
13376 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.FlaggedElement );
13377 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TabIndexedElement );
13382 * Handle the button action being triggered.
13386 OO.ui.ToggleButtonWidget.prototype.onAction = function () {
13387 this.setValue( !this.value );
13393 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
13395 if ( value !== this.value ) {
13396 // Might be called from parent constructor before ButtonElement constructor
13397 if ( this.$button ) {
13398 this.$button.attr( 'aria-pressed', value.toString() );
13400 this.setActive( value );
13404 OO.ui.ToggleButtonWidget.parent.prototype.setValue.call( this, value );
13412 OO.ui.ToggleButtonWidget.prototype.setButtonElement = function ( $button ) {
13413 if ( this.$button ) {
13414 this.$button.removeAttr( 'aria-pressed' );
13416 OO.ui.mixin.ButtonElement.prototype.setButtonElement.call( this, $button );
13417 this.$button.attr( 'aria-pressed', this.value.toString() );
13421 * CapsuleMultiSelectWidgets are something like a {@link OO.ui.ComboBoxInputWidget combo box widget}
13422 * that allows for selecting multiple values.
13424 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
13427 * // Example: A CapsuleMultiSelectWidget.
13428 * var capsule = new OO.ui.CapsuleMultiSelectWidget( {
13429 * label: 'CapsuleMultiSelectWidget',
13430 * selected: [ 'Option 1', 'Option 3' ],
13433 * new OO.ui.MenuOptionWidget( {
13434 * data: 'Option 1',
13435 * label: 'Option One'
13437 * new OO.ui.MenuOptionWidget( {
13438 * data: 'Option 2',
13439 * label: 'Option Two'
13441 * new OO.ui.MenuOptionWidget( {
13442 * data: 'Option 3',
13443 * label: 'Option Three'
13445 * new OO.ui.MenuOptionWidget( {
13446 * data: 'Option 4',
13447 * label: 'Option Four'
13449 * new OO.ui.MenuOptionWidget( {
13450 * data: 'Option 5',
13451 * label: 'Option Five'
13456 * $( 'body' ).append( capsule.$element );
13458 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13461 * @extends OO.ui.Widget
13462 * @mixins OO.ui.mixin.TabIndexedElement
13463 * @mixins OO.ui.mixin.GroupElement
13466 * @param {Object} [config] Configuration options
13467 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
13468 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
13469 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
13470 * If specified, this popup will be shown instead of the menu (but the menu
13471 * will still be used for item labels and allowArbitrary=false). The widgets
13472 * in the popup should use this.addItemsFromData() or this.addItems() as necessary.
13473 * @cfg {jQuery} [$overlay] Render the menu or popup into a separate layer.
13474 * This configuration is useful in cases where the expanded menu is larger than
13475 * its containing `<div>`. The specified overlay layer is usually on top of
13476 * the containing `<div>` and has a larger area. By default, the menu uses
13477 * relative positioning.
13479 OO.ui.CapsuleMultiSelectWidget = function OoUiCapsuleMultiSelectWidget( config ) {
13482 // Configuration initialization
13483 config = config || {};
13485 // Parent constructor
13486 OO.ui.CapsuleMultiSelectWidget.parent.call( this, config );
13488 // Properties (must be set before mixin constructor calls)
13489 this.$input = config.popup ? null : $( '<input>' );
13490 this.$handle = $( '<div>' );
13492 // Mixin constructors
13493 OO.ui.mixin.GroupElement.call( this, config );
13494 if ( config.popup ) {
13495 config.popup = $.extend( {}, config.popup, {
13499 OO.ui.mixin.PopupElement.call( this, config );
13500 $tabFocus = $( '<span>' );
13501 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: $tabFocus } ) );
13505 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
13507 OO.ui.mixin.IndicatorElement.call( this, config );
13508 OO.ui.mixin.IconElement.call( this, config );
13511 this.$content = $( '<div>' );
13512 this.allowArbitrary = !!config.allowArbitrary;
13513 this.$overlay = config.$overlay || this.$element;
13514 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
13517 $input: this.$input,
13518 $container: this.$element,
13519 filterFromInput: true,
13520 disabled: this.isDisabled()
13526 if ( this.popup ) {
13528 focus: this.onFocusForPopup.bind( this )
13530 this.popup.$element.on( 'focusout', this.onPopupFocusOut.bind( this ) );
13531 if ( this.popup.$autoCloseIgnore ) {
13532 this.popup.$autoCloseIgnore.on( 'focusout', this.onPopupFocusOut.bind( this ) );
13534 this.popup.connect( this, {
13535 toggle: function ( visible ) {
13536 $tabFocus.toggle( !visible );
13541 focus: this.onInputFocus.bind( this ),
13542 blur: this.onInputBlur.bind( this ),
13543 'propertychange change click mouseup keydown keyup input cut paste select focus':
13544 OO.ui.debounce( this.updateInputSize.bind( this ) ),
13545 keydown: this.onKeyDown.bind( this ),
13546 keypress: this.onKeyPress.bind( this )
13549 this.menu.connect( this, {
13550 choose: 'onMenuChoose',
13551 add: 'onMenuItemsChange',
13552 remove: 'onMenuItemsChange'
13555 mousedown: this.onMouseDown.bind( this )
13559 if ( this.$input ) {
13560 this.$input.prop( 'disabled', this.isDisabled() );
13561 this.$input.attr( {
13563 'aria-autocomplete': 'list'
13565 this.updateInputSize();
13567 if ( config.data ) {
13568 this.setItemsFromData( config.data );
13570 this.$content.addClass( 'oo-ui-capsuleMultiSelectWidget-content' )
13571 .append( this.$group );
13572 this.$group.addClass( 'oo-ui-capsuleMultiSelectWidget-group' );
13573 this.$handle.addClass( 'oo-ui-capsuleMultiSelectWidget-handle' )
13574 .append( this.$indicator, this.$icon, this.$content );
13575 this.$element.addClass( 'oo-ui-capsuleMultiSelectWidget' )
13576 .append( this.$handle );
13577 if ( this.popup ) {
13578 this.$content.append( $tabFocus );
13579 this.$overlay.append( this.popup.$element );
13581 this.$content.append( this.$input );
13582 this.$overlay.append( this.menu.$element );
13584 this.onMenuItemsChange();
13589 OO.inheritClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.Widget );
13590 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.GroupElement );
13591 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.PopupElement );
13592 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.TabIndexedElement );
13593 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IndicatorElement );
13594 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IconElement );
13601 * A change event is emitted when the set of selected items changes.
13603 * @param {Mixed[]} datas Data of the now-selected items
13609 * Construct a OO.ui.CapsuleItemWidget (or a subclass thereof) from given label and data.
13612 * @param {Mixed} data Custom data of any type.
13613 * @param {string} label The label text.
13614 * @return {OO.ui.CapsuleItemWidget}
13616 OO.ui.CapsuleMultiSelectWidget.prototype.createItemWidget = function ( data, label ) {
13617 return new OO.ui.CapsuleItemWidget( { data: data, label: label } );
13621 * Get the data of the items in the capsule
13622 * @return {Mixed[]}
13624 OO.ui.CapsuleMultiSelectWidget.prototype.getItemsData = function () {
13625 return $.map( this.getItems(), function ( e ) { return e.data; } );
13629 * Set the items in the capsule by providing data
13631 * @param {Mixed[]} datas
13632 * @return {OO.ui.CapsuleMultiSelectWidget}
13634 OO.ui.CapsuleMultiSelectWidget.prototype.setItemsFromData = function ( datas ) {
13637 items = this.getItems();
13639 $.each( datas, function ( i, data ) {
13641 item = menu.getItemFromData( data );
13644 label = item.label;
13645 } else if ( widget.allowArbitrary ) {
13646 label = String( data );
13652 for ( j = 0; j < items.length; j++ ) {
13653 if ( items[ j ].data === data && items[ j ].label === label ) {
13655 items.splice( j, 1 );
13660 item = widget.createItemWidget( data, label );
13662 widget.addItems( [ item ], i );
13665 if ( items.length ) {
13666 widget.removeItems( items );
13673 * Add items to the capsule by providing their data
13675 * @param {Mixed[]} datas
13676 * @return {OO.ui.CapsuleMultiSelectWidget}
13678 OO.ui.CapsuleMultiSelectWidget.prototype.addItemsFromData = function ( datas ) {
13683 $.each( datas, function ( i, data ) {
13686 if ( !widget.getItemFromData( data ) ) {
13687 item = menu.getItemFromData( data );
13689 items.push( widget.createItemWidget( data, item.label ) );
13690 } else if ( widget.allowArbitrary ) {
13691 items.push( widget.createItemWidget( data, String( data ) ) );
13696 if ( items.length ) {
13697 this.addItems( items );
13704 * Remove items by data
13706 * @param {Mixed[]} datas
13707 * @return {OO.ui.CapsuleMultiSelectWidget}
13709 OO.ui.CapsuleMultiSelectWidget.prototype.removeItemsFromData = function ( datas ) {
13713 $.each( datas, function ( i, data ) {
13714 var item = widget.getItemFromData( data );
13716 items.push( item );
13720 if ( items.length ) {
13721 this.removeItems( items );
13730 OO.ui.CapsuleMultiSelectWidget.prototype.addItems = function ( items ) {
13732 oldItems = this.items.slice();
13734 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items );
13736 if ( this.items.length !== oldItems.length ) {
13740 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
13741 same = same && this.items[ i ] === oldItems[ i ];
13745 this.emit( 'change', this.getItemsData() );
13746 this.menu.position();
13755 OO.ui.CapsuleMultiSelectWidget.prototype.removeItems = function ( items ) {
13757 oldItems = this.items.slice();
13759 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
13761 if ( this.items.length !== oldItems.length ) {
13765 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
13766 same = same && this.items[ i ] === oldItems[ i ];
13770 this.emit( 'change', this.getItemsData() );
13771 this.menu.position();
13780 OO.ui.CapsuleMultiSelectWidget.prototype.clearItems = function () {
13781 if ( this.items.length ) {
13782 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
13783 this.emit( 'change', this.getItemsData() );
13784 this.menu.position();
13790 * Get the capsule widget's menu.
13791 * @return {OO.ui.MenuSelectWidget} Menu widget
13793 OO.ui.CapsuleMultiSelectWidget.prototype.getMenu = function () {
13798 * Handle focus events
13801 * @param {jQuery.Event} event
13803 OO.ui.CapsuleMultiSelectWidget.prototype.onInputFocus = function () {
13804 if ( !this.isDisabled() ) {
13805 this.menu.toggle( true );
13810 * Handle blur events
13813 * @param {jQuery.Event} event
13815 OO.ui.CapsuleMultiSelectWidget.prototype.onInputBlur = function () {
13816 if ( this.allowArbitrary && this.$input.val().trim() !== '' ) {
13817 this.addItemsFromData( [ this.$input.val() ] );
13823 * Handle focus events
13826 * @param {jQuery.Event} event
13828 OO.ui.CapsuleMultiSelectWidget.prototype.onFocusForPopup = function () {
13829 if ( !this.isDisabled() ) {
13830 this.popup.setSize( this.$handle.width() );
13831 this.popup.toggle( true );
13832 this.popup.$element.find( '*' )
13833 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
13840 * Handles popup focus out events.
13843 * @param {Event} e Focus out event
13845 OO.ui.CapsuleMultiSelectWidget.prototype.onPopupFocusOut = function () {
13846 var widget = this.popup;
13848 setTimeout( function () {
13850 widget.isVisible() &&
13851 !OO.ui.contains( widget.$element[ 0 ], document.activeElement, true ) &&
13852 ( !widget.$autoCloseIgnore || !widget.$autoCloseIgnore.has( document.activeElement ).length )
13854 widget.toggle( false );
13860 * Handle mouse down events.
13863 * @param {jQuery.Event} e Mouse down event
13865 OO.ui.CapsuleMultiSelectWidget.prototype.onMouseDown = function ( e ) {
13866 if ( e.which === 1 ) {
13870 this.updateInputSize();
13875 * Handle key press events.
13878 * @param {jQuery.Event} e Key press event
13880 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyPress = function ( e ) {
13883 if ( !this.isDisabled() ) {
13884 if ( e.which === OO.ui.Keys.ESCAPE ) {
13889 if ( !this.popup ) {
13890 this.menu.toggle( true );
13891 if ( e.which === OO.ui.Keys.ENTER ) {
13892 item = this.menu.getItemFromLabel( this.$input.val(), true );
13894 this.addItemsFromData( [ item.data ] );
13896 } else if ( this.allowArbitrary && this.$input.val().trim() !== '' ) {
13897 this.addItemsFromData( [ this.$input.val() ] );
13903 // Make sure the input gets resized.
13904 setTimeout( this.updateInputSize.bind( this ), 0 );
13910 * Handle key down events.
13913 * @param {jQuery.Event} e Key down event
13915 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyDown = function ( e ) {
13916 if ( !this.isDisabled() ) {
13917 // 'keypress' event is not triggered for Backspace
13918 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.$input.val() === '' ) {
13919 if ( this.items.length ) {
13920 this.removeItems( this.items.slice( -1 ) );
13928 * Update the dimensions of the text input field to encompass all available area.
13931 * @param {jQuery.Event} e Event of some sort
13933 OO.ui.CapsuleMultiSelectWidget.prototype.updateInputSize = function () {
13934 var $lastItem, direction, contentWidth, currentWidth, bestWidth;
13935 if ( !this.isDisabled() ) {
13936 this.$input.css( 'width', '1em' );
13937 $lastItem = this.$group.children().last();
13938 direction = OO.ui.Element.static.getDir( this.$handle );
13939 contentWidth = this.$input[ 0 ].scrollWidth;
13940 currentWidth = this.$input.width();
13942 if ( contentWidth < currentWidth ) {
13943 // All is fine, don't perform expensive calculations
13947 if ( !$lastItem.length ) {
13948 bestWidth = this.$content.innerWidth();
13950 bestWidth = direction === 'ltr' ?
13951 this.$content.innerWidth() - $lastItem.position().left - $lastItem.outerWidth() :
13952 $lastItem.position().left;
13954 // Some safety margin for sanity, because I *really* don't feel like finding out where the few
13955 // pixels this is off by are coming from.
13957 if ( contentWidth > bestWidth ) {
13958 // This will result in the input getting shifted to the next line
13959 bestWidth = this.$content.innerWidth() - 10;
13961 this.$input.width( Math.floor( bestWidth ) );
13963 this.menu.position();
13968 * Handle menu choose events.
13971 * @param {OO.ui.OptionWidget} item Chosen item
13973 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuChoose = function ( item ) {
13974 if ( item && item.isVisible() ) {
13975 this.addItemsFromData( [ item.getData() ] );
13981 * Handle menu item change events.
13985 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuItemsChange = function () {
13986 this.setItemsFromData( this.getItemsData() );
13987 this.$element.toggleClass( 'oo-ui-capsuleMultiSelectWidget-empty', this.menu.isEmpty() );
13991 * Clear the input field
13994 OO.ui.CapsuleMultiSelectWidget.prototype.clearInput = function () {
13995 if ( this.$input ) {
13996 this.$input.val( '' );
13997 this.updateInputSize();
13999 if ( this.popup ) {
14000 this.popup.toggle( false );
14002 this.menu.toggle( false );
14003 this.menu.selectItem();
14004 this.menu.highlightItem();
14010 OO.ui.CapsuleMultiSelectWidget.prototype.setDisabled = function ( disabled ) {
14014 OO.ui.CapsuleMultiSelectWidget.parent.prototype.setDisabled.call( this, disabled );
14016 if ( this.$input ) {
14017 this.$input.prop( 'disabled', this.isDisabled() );
14020 this.menu.setDisabled( this.isDisabled() );
14022 if ( this.popup ) {
14023 this.popup.setDisabled( this.isDisabled() );
14026 if ( this.items ) {
14027 for ( i = 0, len = this.items.length; i < len; i++ ) {
14028 this.items[ i ].updateDisabled();
14038 * @return {OO.ui.CapsuleMultiSelectWidget}
14040 OO.ui.CapsuleMultiSelectWidget.prototype.focus = function () {
14041 if ( !this.isDisabled() ) {
14042 if ( this.popup ) {
14043 this.popup.setSize( this.$handle.width() );
14044 this.popup.toggle( true );
14045 this.popup.$element.find( '*' )
14046 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
14050 this.updateInputSize();
14051 this.menu.toggle( true );
14052 this.$input.focus();
14059 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiSelectWidget
14060 * CapsuleMultiSelectWidget} to display the selected items.
14063 * @extends OO.ui.Widget
14064 * @mixins OO.ui.mixin.ItemWidget
14065 * @mixins OO.ui.mixin.IndicatorElement
14066 * @mixins OO.ui.mixin.LabelElement
14067 * @mixins OO.ui.mixin.FlaggedElement
14068 * @mixins OO.ui.mixin.TabIndexedElement
14071 * @param {Object} [config] Configuration options
14073 OO.ui.CapsuleItemWidget = function OoUiCapsuleItemWidget( config ) {
14074 // Configuration initialization
14075 config = config || {};
14077 // Parent constructor
14078 OO.ui.CapsuleItemWidget.parent.call( this, config );
14080 // Properties (must be set before mixin constructor calls)
14081 this.$indicator = $( '<span>' );
14083 // Mixin constructors
14084 OO.ui.mixin.ItemWidget.call( this );
14085 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$indicator, indicator: 'clear' } ) );
14086 OO.ui.mixin.LabelElement.call( this, config );
14087 OO.ui.mixin.FlaggedElement.call( this, config );
14088 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
14091 this.$indicator.on( {
14092 keydown: this.onCloseKeyDown.bind( this ),
14093 click: this.onCloseClick.bind( this )
14098 .addClass( 'oo-ui-capsuleItemWidget' )
14099 .append( this.$indicator, this.$label );
14104 OO.inheritClass( OO.ui.CapsuleItemWidget, OO.ui.Widget );
14105 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.ItemWidget );
14106 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.IndicatorElement );
14107 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.LabelElement );
14108 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.FlaggedElement );
14109 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.TabIndexedElement );
14114 * Handle close icon clicks
14115 * @param {jQuery.Event} event
14117 OO.ui.CapsuleItemWidget.prototype.onCloseClick = function () {
14118 var element = this.getElementGroup();
14120 if ( !this.isDisabled() && element && $.isFunction( element.removeItems ) ) {
14121 element.removeItems( [ this ] );
14127 * Handle close keyboard events
14128 * @param {jQuery.Event} event Key down event
14130 OO.ui.CapsuleItemWidget.prototype.onCloseKeyDown = function ( e ) {
14131 if ( !this.isDisabled() && $.isFunction( this.getElementGroup().removeItems ) ) {
14132 switch ( e.which ) {
14133 case OO.ui.Keys.ENTER:
14134 case OO.ui.Keys.BACKSPACE:
14135 case OO.ui.Keys.SPACE:
14136 this.getElementGroup().removeItems( [ this ] );
14143 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
14144 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
14145 * users can interact with it.
14147 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
14148 * OO.ui.DropdownInputWidget instead.
14151 * // Example: A DropdownWidget with a menu that contains three options
14152 * var dropDown = new OO.ui.DropdownWidget( {
14153 * label: 'Dropdown menu: Select a menu option',
14156 * new OO.ui.MenuOptionWidget( {
14160 * new OO.ui.MenuOptionWidget( {
14164 * new OO.ui.MenuOptionWidget( {
14172 * $( 'body' ).append( dropDown.$element );
14174 * dropDown.getMenu().selectItemByData( 'b' );
14176 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
14178 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
14180 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
14183 * @extends OO.ui.Widget
14184 * @mixins OO.ui.mixin.IconElement
14185 * @mixins OO.ui.mixin.IndicatorElement
14186 * @mixins OO.ui.mixin.LabelElement
14187 * @mixins OO.ui.mixin.TitledElement
14188 * @mixins OO.ui.mixin.TabIndexedElement
14191 * @param {Object} [config] Configuration options
14192 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
14193 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
14194 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
14195 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
14197 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
14198 // Configuration initialization
14199 config = $.extend( { indicator: 'down' }, config );
14201 // Parent constructor
14202 OO.ui.DropdownWidget.parent.call( this, config );
14204 // Properties (must be set before TabIndexedElement constructor call)
14205 this.$handle = this.$( '<span>' );
14206 this.$overlay = config.$overlay || this.$element;
14208 // Mixin constructors
14209 OO.ui.mixin.IconElement.call( this, config );
14210 OO.ui.mixin.IndicatorElement.call( this, config );
14211 OO.ui.mixin.LabelElement.call( this, config );
14212 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
14213 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
14216 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend( {
14218 $container: this.$element
14219 }, config.menu ) );
14223 click: this.onClick.bind( this ),
14224 keypress: this.onKeyPress.bind( this )
14226 this.menu.connect( this, { select: 'onMenuSelect' } );
14230 .addClass( 'oo-ui-dropdownWidget-handle' )
14231 .append( this.$icon, this.$label, this.$indicator );
14233 .addClass( 'oo-ui-dropdownWidget' )
14234 .append( this.$handle );
14235 this.$overlay.append( this.menu.$element );
14240 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
14241 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement );
14242 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement );
14243 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement );
14244 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement );
14245 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement );
14252 * @return {OO.ui.MenuSelectWidget} Menu of widget
14254 OO.ui.DropdownWidget.prototype.getMenu = function () {
14259 * Handles menu select events.
14262 * @param {OO.ui.MenuOptionWidget} item Selected menu item
14264 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
14268 this.setLabel( null );
14272 selectedLabel = item.getLabel();
14274 // If the label is a DOM element, clone it, because setLabel will append() it
14275 if ( selectedLabel instanceof jQuery ) {
14276 selectedLabel = selectedLabel.clone();
14279 this.setLabel( selectedLabel );
14283 * Handle mouse click events.
14286 * @param {jQuery.Event} e Mouse click event
14288 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
14289 if ( !this.isDisabled() && e.which === 1 ) {
14290 this.menu.toggle();
14296 * Handle key press events.
14299 * @param {jQuery.Event} e Key press event
14301 OO.ui.DropdownWidget.prototype.onKeyPress = function ( e ) {
14302 if ( !this.isDisabled() &&
14303 ( ( e.which === OO.ui.Keys.SPACE && !this.menu.isVisible() ) || e.which === OO.ui.Keys.ENTER )
14305 this.menu.toggle();
14311 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
14312 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
14313 * OO.ui.mixin.IndicatorElement indicators}.
14314 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14317 * // Example of a file select widget
14318 * var selectFile = new OO.ui.SelectFileWidget();
14319 * $( 'body' ).append( selectFile.$element );
14321 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
14324 * @extends OO.ui.Widget
14325 * @mixins OO.ui.mixin.IconElement
14326 * @mixins OO.ui.mixin.IndicatorElement
14327 * @mixins OO.ui.mixin.PendingElement
14328 * @mixins OO.ui.mixin.LabelElement
14331 * @param {Object} [config] Configuration options
14332 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
14333 * @cfg {string} [placeholder] Text to display when no file is selected.
14334 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
14335 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
14336 * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
14337 * @cfg {boolean} [dragDropUI=false] Deprecated alias for showDropTarget
14339 OO.ui.SelectFileWidget = function OoUiSelectFileWidget( config ) {
14342 // TODO: Remove in next release
14343 if ( config && config.dragDropUI ) {
14344 config.showDropTarget = true;
14347 // Configuration initialization
14348 config = $.extend( {
14350 placeholder: OO.ui.msg( 'ooui-selectfile-placeholder' ),
14351 notsupported: OO.ui.msg( 'ooui-selectfile-not-supported' ),
14353 showDropTarget: false
14356 // Parent constructor
14357 OO.ui.SelectFileWidget.parent.call( this, config );
14359 // Mixin constructors
14360 OO.ui.mixin.IconElement.call( this, config );
14361 OO.ui.mixin.IndicatorElement.call( this, config );
14362 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$info } ) );
14363 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { autoFitLabel: true } ) );
14366 this.$info = $( '<span>' );
14369 this.showDropTarget = config.showDropTarget;
14370 this.isSupported = this.constructor.static.isSupported();
14371 this.currentFile = null;
14372 if ( Array.isArray( config.accept ) ) {
14373 this.accept = config.accept;
14375 this.accept = null;
14377 this.placeholder = config.placeholder;
14378 this.notsupported = config.notsupported;
14379 this.onFileSelectedHandler = this.onFileSelected.bind( this );
14381 this.selectButton = new OO.ui.ButtonWidget( {
14382 classes: [ 'oo-ui-selectFileWidget-selectButton' ],
14383 label: OO.ui.msg( 'ooui-selectfile-button-select' ),
14384 disabled: this.disabled || !this.isSupported
14387 this.clearButton = new OO.ui.ButtonWidget( {
14388 classes: [ 'oo-ui-selectFileWidget-clearButton' ],
14391 disabled: this.disabled
14395 this.selectButton.$button.on( {
14396 keypress: this.onKeyPress.bind( this )
14398 this.clearButton.connect( this, {
14399 click: 'onClearClick'
14401 if ( config.droppable ) {
14402 dragHandler = this.onDragEnterOrOver.bind( this );
14403 this.$element.on( {
14404 dragenter: dragHandler,
14405 dragover: dragHandler,
14406 dragleave: this.onDragLeave.bind( this ),
14407 drop: this.onDrop.bind( this )
14414 this.$label.addClass( 'oo-ui-selectFileWidget-label' );
14416 .addClass( 'oo-ui-selectFileWidget-info' )
14417 .append( this.$icon, this.$label, this.clearButton.$element, this.$indicator );
14419 .addClass( 'oo-ui-selectFileWidget' )
14420 .append( this.$info, this.selectButton.$element );
14421 if ( config.droppable && config.showDropTarget ) {
14422 this.$dropTarget = $( '<div>' )
14423 .addClass( 'oo-ui-selectFileWidget-dropTarget' )
14424 .text( OO.ui.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
14426 click: this.onDropTargetClick.bind( this )
14428 this.$element.prepend( this.$dropTarget );
14434 OO.inheritClass( OO.ui.SelectFileWidget, OO.ui.Widget );
14435 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IconElement );
14436 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IndicatorElement );
14437 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.PendingElement );
14438 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.LabelElement );
14440 /* Static Properties */
14443 * Check if this widget is supported
14446 * @return {boolean}
14448 OO.ui.SelectFileWidget.static.isSupported = function () {
14450 if ( OO.ui.SelectFileWidget.static.isSupportedCache === null ) {
14451 $input = $( '<input type="file">' );
14452 OO.ui.SelectFileWidget.static.isSupportedCache = $input[ 0 ].files !== undefined;
14454 return OO.ui.SelectFileWidget.static.isSupportedCache;
14457 OO.ui.SelectFileWidget.static.isSupportedCache = null;
14464 * A change event is emitted when the on/off state of the toggle changes.
14466 * @param {File|null} value New value
14472 * Get the current value of the field
14474 * @return {File|null}
14476 OO.ui.SelectFileWidget.prototype.getValue = function () {
14477 return this.currentFile;
14481 * Set the current value of the field
14483 * @param {File|null} file File to select
14485 OO.ui.SelectFileWidget.prototype.setValue = function ( file ) {
14486 if ( this.currentFile !== file ) {
14487 this.currentFile = file;
14489 this.emit( 'change', this.currentFile );
14494 * Focus the widget.
14496 * Focusses the select file button.
14500 OO.ui.SelectFileWidget.prototype.focus = function () {
14501 this.selectButton.$button[ 0 ].focus();
14506 * Update the user interface when a file is selected or unselected
14510 OO.ui.SelectFileWidget.prototype.updateUI = function () {
14512 if ( !this.isSupported ) {
14513 this.$element.addClass( 'oo-ui-selectFileWidget-notsupported' );
14514 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
14515 this.setLabel( this.notsupported );
14517 this.$element.addClass( 'oo-ui-selectFileWidget-supported' );
14518 if ( this.currentFile ) {
14519 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
14521 if ( this.currentFile.type !== '' ) {
14522 $label = $label.add( $( '<span>' ).addClass( 'oo-ui-selectFileWidget-fileType' ).text( this.currentFile.type ) );
14524 $label = $label.add( $( '<span>' ).text( this.currentFile.name ) );
14525 this.setLabel( $label );
14527 this.$element.addClass( 'oo-ui-selectFileWidget-empty' );
14528 this.setLabel( this.placeholder );
14534 * Add the input to the widget
14538 OO.ui.SelectFileWidget.prototype.addInput = function () {
14539 if ( this.$input ) {
14540 this.$input.remove();
14543 if ( !this.isSupported ) {
14544 this.$input = null;
14548 this.$input = $( '<input type="file">' );
14549 this.$input.on( 'change', this.onFileSelectedHandler );
14550 this.$input.attr( {
14553 if ( this.accept ) {
14554 this.$input.attr( 'accept', this.accept.join( ', ' ) );
14556 this.selectButton.$button.append( this.$input );
14560 * Determine if we should accept this file
14563 * @param {string} File MIME type
14564 * @return {boolean}
14566 OO.ui.SelectFileWidget.prototype.isAllowedType = function ( mimeType ) {
14569 if ( !this.accept || !mimeType ) {
14573 for ( i = 0; i < this.accept.length; i++ ) {
14574 mimeTest = this.accept[ i ];
14575 if ( mimeTest === mimeType ) {
14577 } else if ( mimeTest.substr( -2 ) === '/*' ) {
14578 mimeTest = mimeTest.substr( 0, mimeTest.length - 1 );
14579 if ( mimeType.substr( 0, mimeTest.length ) === mimeTest ) {
14589 * Handle file selection from the input
14592 * @param {jQuery.Event} e
14594 OO.ui.SelectFileWidget.prototype.onFileSelected = function ( e ) {
14595 var file = OO.getProp( e.target, 'files', 0 ) || null;
14597 if ( file && !this.isAllowedType( file.type ) ) {
14601 this.setValue( file );
14606 * Handle clear button click events.
14610 OO.ui.SelectFileWidget.prototype.onClearClick = function () {
14611 this.setValue( null );
14616 * Handle key press events.
14619 * @param {jQuery.Event} e Key press event
14621 OO.ui.SelectFileWidget.prototype.onKeyPress = function ( e ) {
14622 if ( this.isSupported && !this.isDisabled() && this.$input &&
14623 ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
14625 this.$input.click();
14631 * Handle drop target click events.
14634 * @param {jQuery.Event} e Key press event
14636 OO.ui.SelectFileWidget.prototype.onDropTargetClick = function () {
14637 if ( this.isSupported && !this.isDisabled() && this.$input ) {
14638 this.$input.click();
14644 * Handle drag enter and over events
14647 * @param {jQuery.Event} e Drag event
14649 OO.ui.SelectFileWidget.prototype.onDragEnterOrOver = function ( e ) {
14651 droppableFile = false,
14652 dt = e.originalEvent.dataTransfer;
14654 e.preventDefault();
14655 e.stopPropagation();
14657 if ( this.isDisabled() || !this.isSupported ) {
14658 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14659 dt.dropEffect = 'none';
14663 // DataTransferItem and File both have a type property, but in Chrome files
14664 // have no information at this point.
14665 itemOrFile = OO.getProp( dt, 'items', 0 ) || OO.getProp( dt, 'files', 0 );
14666 if ( itemOrFile ) {
14667 if ( this.isAllowedType( itemOrFile.type ) ) {
14668 droppableFile = true;
14670 // dt.types is Array-like, but not an Array
14671 } else if ( Array.prototype.indexOf.call( OO.getProp( dt, 'types' ) || [], 'Files' ) !== -1 ) {
14672 // File information is not available at this point for security so just assume
14673 // it is acceptable for now.
14674 // https://bugzilla.mozilla.org/show_bug.cgi?id=640534
14675 droppableFile = true;
14678 this.$element.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile );
14679 if ( !droppableFile ) {
14680 dt.dropEffect = 'none';
14687 * Handle drag leave events
14690 * @param {jQuery.Event} e Drag event
14692 OO.ui.SelectFileWidget.prototype.onDragLeave = function () {
14693 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14697 * Handle drop events
14700 * @param {jQuery.Event} e Drop event
14702 OO.ui.SelectFileWidget.prototype.onDrop = function ( e ) {
14704 dt = e.originalEvent.dataTransfer;
14706 e.preventDefault();
14707 e.stopPropagation();
14708 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14710 if ( this.isDisabled() || !this.isSupported ) {
14714 file = OO.getProp( dt, 'files', 0 );
14715 if ( file && !this.isAllowedType( file.type ) ) {
14719 this.setValue( file );
14728 OO.ui.SelectFileWidget.prototype.setDisabled = function ( disabled ) {
14729 OO.ui.SelectFileWidget.parent.prototype.setDisabled.call( this, disabled );
14730 if ( this.selectButton ) {
14731 this.selectButton.setDisabled( disabled );
14733 if ( this.clearButton ) {
14734 this.clearButton.setDisabled( disabled );
14740 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
14741 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
14742 * for a list of icons included in the library.
14745 * // An icon widget with a label
14746 * var myIcon = new OO.ui.IconWidget( {
14748 * iconTitle: 'Help'
14750 * // Create a label.
14751 * var iconLabel = new OO.ui.LabelWidget( {
14754 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
14756 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
14759 * @extends OO.ui.Widget
14760 * @mixins OO.ui.mixin.IconElement
14761 * @mixins OO.ui.mixin.TitledElement
14762 * @mixins OO.ui.mixin.FlaggedElement
14765 * @param {Object} [config] Configuration options
14767 OO.ui.IconWidget = function OoUiIconWidget( config ) {
14768 // Configuration initialization
14769 config = config || {};
14771 // Parent constructor
14772 OO.ui.IconWidget.parent.call( this, config );
14774 // Mixin constructors
14775 OO.ui.mixin.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
14776 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
14777 OO.ui.mixin.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) );
14780 this.$element.addClass( 'oo-ui-iconWidget' );
14785 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
14786 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.IconElement );
14787 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.TitledElement );
14788 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.FlaggedElement );
14790 /* Static Properties */
14792 OO.ui.IconWidget.static.tagName = 'span';
14795 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
14796 * attention to the status of an item or to clarify the function of a control. For a list of
14797 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
14800 * // Example of an indicator widget
14801 * var indicator1 = new OO.ui.IndicatorWidget( {
14802 * indicator: 'alert'
14805 * // Create a fieldset layout to add a label
14806 * var fieldset = new OO.ui.FieldsetLayout();
14807 * fieldset.addItems( [
14808 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
14810 * $( 'body' ).append( fieldset.$element );
14812 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
14815 * @extends OO.ui.Widget
14816 * @mixins OO.ui.mixin.IndicatorElement
14817 * @mixins OO.ui.mixin.TitledElement
14820 * @param {Object} [config] Configuration options
14822 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
14823 // Configuration initialization
14824 config = config || {};
14826 // Parent constructor
14827 OO.ui.IndicatorWidget.parent.call( this, config );
14829 // Mixin constructors
14830 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
14831 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
14834 this.$element.addClass( 'oo-ui-indicatorWidget' );
14839 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
14840 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.IndicatorElement );
14841 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.TitledElement );
14843 /* Static Properties */
14845 OO.ui.IndicatorWidget.static.tagName = 'span';
14848 * InputWidget is the base class for all input widgets, which
14849 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
14850 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
14851 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14853 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14857 * @extends OO.ui.Widget
14858 * @mixins OO.ui.mixin.FlaggedElement
14859 * @mixins OO.ui.mixin.TabIndexedElement
14860 * @mixins OO.ui.mixin.TitledElement
14861 * @mixins OO.ui.mixin.AccessKeyedElement
14864 * @param {Object} [config] Configuration options
14865 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
14866 * @cfg {string} [value=''] The value of the input.
14867 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
14868 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
14869 * before it is accepted.
14871 OO.ui.InputWidget = function OoUiInputWidget( config ) {
14872 // Configuration initialization
14873 config = config || {};
14875 // Parent constructor
14876 OO.ui.InputWidget.parent.call( this, config );
14879 this.$input = this.getInputElement( config );
14881 this.inputFilter = config.inputFilter;
14883 // Mixin constructors
14884 OO.ui.mixin.FlaggedElement.call( this, config );
14885 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
14886 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
14887 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$input } ) );
14890 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
14894 .addClass( 'oo-ui-inputWidget-input' )
14895 .attr( 'name', config.name )
14896 .prop( 'disabled', this.isDisabled() );
14898 .addClass( 'oo-ui-inputWidget' )
14899 .append( this.$input );
14900 this.setValue( config.value );
14901 this.setAccessKey( config.accessKey );
14902 if ( config.dir ) {
14903 this.setDir( config.dir );
14909 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
14910 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.FlaggedElement );
14911 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement );
14912 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TitledElement );
14913 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.AccessKeyedElement );
14915 /* Static Properties */
14917 OO.ui.InputWidget.static.supportsSimpleLabel = true;
14919 /* Static Methods */
14924 OO.ui.InputWidget.static.reusePreInfuseDOM = function ( node, config ) {
14925 config = OO.ui.InputWidget.parent.static.reusePreInfuseDOM( node, config );
14926 // Reusing $input lets browsers preserve inputted values across page reloads (T114134)
14927 config.$input = $( node ).find( '.oo-ui-inputWidget-input' );
14934 OO.ui.InputWidget.static.gatherPreInfuseState = function ( node, config ) {
14935 var state = OO.ui.InputWidget.parent.static.gatherPreInfuseState( node, config );
14936 state.value = config.$input.val();
14937 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
14938 state.focus = config.$input.is( ':focus' );
14947 * A change event is emitted when the value of the input changes.
14949 * @param {string} value
14955 * Get input element.
14957 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
14958 * different circumstances. The element must have a `value` property (like form elements).
14961 * @param {Object} config Configuration options
14962 * @return {jQuery} Input element
14964 OO.ui.InputWidget.prototype.getInputElement = function ( config ) {
14965 // See #reusePreInfuseDOM about config.$input
14966 return config.$input || $( '<input>' );
14970 * Handle potentially value-changing events.
14973 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
14975 OO.ui.InputWidget.prototype.onEdit = function () {
14977 if ( !this.isDisabled() ) {
14978 // Allow the stack to clear so the value will be updated
14979 setTimeout( function () {
14980 widget.setValue( widget.$input.val() );
14986 * Get the value of the input.
14988 * @return {string} Input value
14990 OO.ui.InputWidget.prototype.getValue = function () {
14991 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14992 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14993 var value = this.$input.val();
14994 if ( this.value !== value ) {
14995 this.setValue( value );
15001 * Set the directionality of the input, either RTL (right-to-left) or LTR (left-to-right).
15003 * @deprecated since v0.13.1, use #setDir directly
15004 * @param {boolean} isRTL Directionality is right-to-left
15007 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
15008 this.setDir( isRTL ? 'rtl' : 'ltr' );
15013 * Set the directionality of the input.
15015 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
15018 OO.ui.InputWidget.prototype.setDir = function ( dir ) {
15019 this.$input.prop( 'dir', dir );
15024 * Set the value of the input.
15026 * @param {string} value New value
15030 OO.ui.InputWidget.prototype.setValue = function ( value ) {
15031 value = this.cleanUpValue( value );
15032 // Update the DOM if it has changed. Note that with cleanUpValue, it
15033 // is possible for the DOM value to change without this.value changing.
15034 if ( this.$input.val() !== value ) {
15035 this.$input.val( value );
15037 if ( this.value !== value ) {
15038 this.value = value;
15039 this.emit( 'change', this.value );
15045 * Set the input's access key.
15046 * FIXME: This is the same code as in OO.ui.mixin.ButtonElement, maybe find a better place for it?
15048 * @param {string} accessKey Input's access key, use empty string to remove
15051 OO.ui.InputWidget.prototype.setAccessKey = function ( accessKey ) {
15052 accessKey = typeof accessKey === 'string' && accessKey.length ? accessKey : null;
15054 if ( this.accessKey !== accessKey ) {
15055 if ( this.$input ) {
15056 if ( accessKey !== null ) {
15057 this.$input.attr( 'accesskey', accessKey );
15059 this.$input.removeAttr( 'accesskey' );
15062 this.accessKey = accessKey;
15069 * Clean up incoming value.
15071 * Ensures value is a string, and converts undefined and null to empty string.
15074 * @param {string} value Original value
15075 * @return {string} Cleaned up value
15077 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
15078 if ( value === undefined || value === null ) {
15080 } else if ( this.inputFilter ) {
15081 return this.inputFilter( String( value ) );
15083 return String( value );
15088 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
15089 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
15092 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
15093 if ( !this.isDisabled() ) {
15094 if ( this.$input.is( ':checkbox, :radio' ) ) {
15095 this.$input.click();
15097 if ( this.$input.is( ':input' ) ) {
15098 this.$input[ 0 ].focus();
15106 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
15107 OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state );
15108 if ( this.$input ) {
15109 this.$input.prop( 'disabled', this.isDisabled() );
15119 OO.ui.InputWidget.prototype.focus = function () {
15120 this.$input[ 0 ].focus();
15129 OO.ui.InputWidget.prototype.blur = function () {
15130 this.$input[ 0 ].blur();
15137 OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) {
15138 OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state );
15139 if ( state.value !== undefined && state.value !== this.getValue() ) {
15140 this.setValue( state.value );
15142 if ( state.focus ) {
15148 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
15149 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
15150 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
15151 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
15152 * [OOjs UI documentation on MediaWiki] [1] for more information.
15155 * // A ButtonInputWidget rendered as an HTML button, the default.
15156 * var button = new OO.ui.ButtonInputWidget( {
15157 * label: 'Input button',
15161 * $( 'body' ).append( button.$element );
15163 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
15166 * @extends OO.ui.InputWidget
15167 * @mixins OO.ui.mixin.ButtonElement
15168 * @mixins OO.ui.mixin.IconElement
15169 * @mixins OO.ui.mixin.IndicatorElement
15170 * @mixins OO.ui.mixin.LabelElement
15171 * @mixins OO.ui.mixin.TitledElement
15174 * @param {Object} [config] Configuration options
15175 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
15176 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
15177 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
15178 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
15179 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
15181 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
15182 // Configuration initialization
15183 config = $.extend( { type: 'button', useInputTag: false }, config );
15185 // Properties (must be set before parent constructor, which calls #setValue)
15186 this.useInputTag = config.useInputTag;
15188 // Parent constructor
15189 OO.ui.ButtonInputWidget.parent.call( this, config );
15191 // Mixin constructors
15192 OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
15193 OO.ui.mixin.IconElement.call( this, config );
15194 OO.ui.mixin.IndicatorElement.call( this, config );
15195 OO.ui.mixin.LabelElement.call( this, config );
15196 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
15199 if ( !config.useInputTag ) {
15200 this.$input.append( this.$icon, this.$label, this.$indicator );
15202 this.$element.addClass( 'oo-ui-buttonInputWidget' );
15207 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
15208 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement );
15209 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement );
15210 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement );
15211 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement );
15212 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.TitledElement );
15214 /* Static Properties */
15217 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
15218 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
15220 OO.ui.ButtonInputWidget.static.supportsSimpleLabel = false;
15228 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
15230 // See InputWidget#reusePreInfuseDOM about config.$input
15231 if ( config.$input ) {
15232 return config.$input.empty();
15234 type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ? config.type : 'button';
15235 return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' );
15241 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
15243 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
15244 * text, or `null` for no label
15247 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
15248 OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label );
15250 if ( this.useInputTag ) {
15251 if ( typeof label === 'function' ) {
15252 label = OO.ui.resolveMsg( label );
15254 if ( label instanceof jQuery ) {
15255 label = label.text();
15260 this.$input.val( label );
15267 * Set the value of the input.
15269 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
15270 * they do not support {@link #value values}.
15272 * @param {string} value New value
15275 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
15276 if ( !this.useInputTag ) {
15277 OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value );
15283 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
15284 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
15285 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
15286 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
15288 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15291 * // An example of selected, unselected, and disabled checkbox inputs
15292 * var checkbox1=new OO.ui.CheckboxInputWidget( {
15296 * var checkbox2=new OO.ui.CheckboxInputWidget( {
15299 * var checkbox3=new OO.ui.CheckboxInputWidget( {
15303 * // Create a fieldset layout with fields for each checkbox.
15304 * var fieldset = new OO.ui.FieldsetLayout( {
15305 * label: 'Checkboxes'
15307 * fieldset.addItems( [
15308 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
15309 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
15310 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
15312 * $( 'body' ).append( fieldset.$element );
15314 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15317 * @extends OO.ui.InputWidget
15320 * @param {Object} [config] Configuration options
15321 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
15323 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
15324 // Configuration initialization
15325 config = config || {};
15327 // Parent constructor
15328 OO.ui.CheckboxInputWidget.parent.call( this, config );
15332 .addClass( 'oo-ui-checkboxInputWidget' )
15333 // Required for pretty styling in MediaWiki theme
15334 .append( $( '<span>' ) );
15335 this.setSelected( config.selected !== undefined ? config.selected : false );
15340 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
15342 /* Static Methods */
15347 OO.ui.CheckboxInputWidget.static.gatherPreInfuseState = function ( node, config ) {
15348 var state = OO.ui.CheckboxInputWidget.parent.static.gatherPreInfuseState( node, config );
15349 state.checked = config.$input.prop( 'checked' );
15359 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
15360 return $( '<input type="checkbox" />' );
15366 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
15368 if ( !this.isDisabled() ) {
15369 // Allow the stack to clear so the value will be updated
15370 setTimeout( function () {
15371 widget.setSelected( widget.$input.prop( 'checked' ) );
15377 * Set selection state of this checkbox.
15379 * @param {boolean} state `true` for selected
15382 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
15384 if ( this.selected !== state ) {
15385 this.selected = state;
15386 this.$input.prop( 'checked', this.selected );
15387 this.emit( 'change', this.selected );
15393 * Check if this checkbox is selected.
15395 * @return {boolean} Checkbox is selected
15397 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
15398 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
15399 // it, and we won't know unless they're kind enough to trigger a 'change' event.
15400 var selected = this.$input.prop( 'checked' );
15401 if ( this.selected !== selected ) {
15402 this.setSelected( selected );
15404 return this.selected;
15410 OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) {
15411 OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
15412 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
15413 this.setSelected( state.checked );
15418 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
15419 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15420 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15421 * more information about input widgets.
15423 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
15424 * are no options. If no `value` configuration option is provided, the first option is selected.
15425 * If you need a state representing no value (no option being selected), use a DropdownWidget.
15427 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
15430 * // Example: A DropdownInputWidget with three options
15431 * var dropdownInput = new OO.ui.DropdownInputWidget( {
15433 * { data: 'a', label: 'First' },
15434 * { data: 'b', label: 'Second'},
15435 * { data: 'c', label: 'Third' }
15438 * $( 'body' ).append( dropdownInput.$element );
15440 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15443 * @extends OO.ui.InputWidget
15444 * @mixins OO.ui.mixin.TitledElement
15447 * @param {Object} [config] Configuration options
15448 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15449 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
15451 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
15452 // Configuration initialization
15453 config = config || {};
15455 // Properties (must be done before parent constructor which calls #setDisabled)
15456 this.dropdownWidget = new OO.ui.DropdownWidget( config.dropdown );
15458 // Parent constructor
15459 OO.ui.DropdownInputWidget.parent.call( this, config );
15461 // Mixin constructors
15462 OO.ui.mixin.TitledElement.call( this, config );
15465 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
15468 this.setOptions( config.options || [] );
15470 .addClass( 'oo-ui-dropdownInputWidget' )
15471 .append( this.dropdownWidget.$element );
15476 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
15477 OO.mixinClass( OO.ui.DropdownInputWidget, OO.ui.mixin.TitledElement );
15485 OO.ui.DropdownInputWidget.prototype.getInputElement = function ( config ) {
15486 // See InputWidget#reusePreInfuseDOM about config.$input
15487 if ( config.$input ) {
15488 return config.$input.addClass( 'oo-ui-element-hidden' );
15490 return $( '<input type="hidden">' );
15494 * Handles menu select events.
15497 * @param {OO.ui.MenuOptionWidget} item Selected menu item
15499 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
15500 this.setValue( item.getData() );
15506 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
15507 value = this.cleanUpValue( value );
15508 this.dropdownWidget.getMenu().selectItemByData( value );
15509 OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value );
15516 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
15517 this.dropdownWidget.setDisabled( state );
15518 OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state );
15523 * Set the options available for this input.
15525 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15528 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
15530 value = this.getValue(),
15533 // Rebuild the dropdown menu
15534 this.dropdownWidget.getMenu()
15536 .addItems( options.map( function ( opt ) {
15537 var optValue = widget.cleanUpValue( opt.data );
15538 return new OO.ui.MenuOptionWidget( {
15540 label: opt.label !== undefined ? opt.label : optValue
15544 // Restore the previous value, or reset to something sensible
15545 if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) {
15546 // Previous value is still available, ensure consistency with the dropdown
15547 this.setValue( value );
15549 // No longer valid, reset
15550 if ( options.length ) {
15551 this.setValue( options[ 0 ].data );
15561 OO.ui.DropdownInputWidget.prototype.focus = function () {
15562 this.dropdownWidget.getMenu().toggle( true );
15569 OO.ui.DropdownInputWidget.prototype.blur = function () {
15570 this.dropdownWidget.getMenu().toggle( false );
15575 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
15576 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
15577 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
15578 * please see the [OOjs UI documentation on MediaWiki][1].
15580 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15583 * // An example of selected, unselected, and disabled radio inputs
15584 * var radio1 = new OO.ui.RadioInputWidget( {
15588 * var radio2 = new OO.ui.RadioInputWidget( {
15591 * var radio3 = new OO.ui.RadioInputWidget( {
15595 * // Create a fieldset layout with fields for each radio button.
15596 * var fieldset = new OO.ui.FieldsetLayout( {
15597 * label: 'Radio inputs'
15599 * fieldset.addItems( [
15600 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
15601 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
15602 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
15604 * $( 'body' ).append( fieldset.$element );
15606 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15609 * @extends OO.ui.InputWidget
15612 * @param {Object} [config] Configuration options
15613 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
15615 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
15616 // Configuration initialization
15617 config = config || {};
15619 // Parent constructor
15620 OO.ui.RadioInputWidget.parent.call( this, config );
15624 .addClass( 'oo-ui-radioInputWidget' )
15625 // Required for pretty styling in MediaWiki theme
15626 .append( $( '<span>' ) );
15627 this.setSelected( config.selected !== undefined ? config.selected : false );
15632 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
15634 /* Static Methods */
15639 OO.ui.RadioInputWidget.static.gatherPreInfuseState = function ( node, config ) {
15640 var state = OO.ui.RadioInputWidget.parent.static.gatherPreInfuseState( node, config );
15641 state.checked = config.$input.prop( 'checked' );
15651 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
15652 return $( '<input type="radio" />' );
15658 OO.ui.RadioInputWidget.prototype.onEdit = function () {
15659 // RadioInputWidget doesn't track its state.
15663 * Set selection state of this radio button.
15665 * @param {boolean} state `true` for selected
15668 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
15669 // RadioInputWidget doesn't track its state.
15670 this.$input.prop( 'checked', state );
15675 * Check if this radio button is selected.
15677 * @return {boolean} Radio is selected
15679 OO.ui.RadioInputWidget.prototype.isSelected = function () {
15680 return this.$input.prop( 'checked' );
15686 OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) {
15687 OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
15688 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
15689 this.setSelected( state.checked );
15694 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
15695 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15696 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15697 * more information about input widgets.
15699 * This and OO.ui.DropdownInputWidget support the same configuration options.
15702 * // Example: A RadioSelectInputWidget with three options
15703 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
15705 * { data: 'a', label: 'First' },
15706 * { data: 'b', label: 'Second'},
15707 * { data: 'c', label: 'Third' }
15710 * $( 'body' ).append( radioSelectInput.$element );
15712 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15715 * @extends OO.ui.InputWidget
15718 * @param {Object} [config] Configuration options
15719 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15721 OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) {
15722 // Configuration initialization
15723 config = config || {};
15725 // Properties (must be done before parent constructor which calls #setDisabled)
15726 this.radioSelectWidget = new OO.ui.RadioSelectWidget();
15728 // Parent constructor
15729 OO.ui.RadioSelectInputWidget.parent.call( this, config );
15732 this.radioSelectWidget.connect( this, { select: 'onMenuSelect' } );
15735 this.setOptions( config.options || [] );
15737 .addClass( 'oo-ui-radioSelectInputWidget' )
15738 .append( this.radioSelectWidget.$element );
15743 OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget );
15745 /* Static Properties */
15747 OO.ui.RadioSelectInputWidget.static.supportsSimpleLabel = false;
15749 /* Static Methods */
15754 OO.ui.RadioSelectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
15755 var state = OO.ui.RadioSelectInputWidget.parent.static.gatherPreInfuseState( node, config );
15756 state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
15766 OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () {
15767 return $( '<input type="hidden">' );
15771 * Handles menu select events.
15774 * @param {OO.ui.RadioOptionWidget} item Selected menu item
15776 OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) {
15777 this.setValue( item.getData() );
15783 OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) {
15784 value = this.cleanUpValue( value );
15785 this.radioSelectWidget.selectItemByData( value );
15786 OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value );
15793 OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) {
15794 this.radioSelectWidget.setDisabled( state );
15795 OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state );
15800 * Set the options available for this input.
15802 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15805 OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) {
15807 value = this.getValue(),
15810 // Rebuild the radioSelect menu
15811 this.radioSelectWidget
15813 .addItems( options.map( function ( opt ) {
15814 var optValue = widget.cleanUpValue( opt.data );
15815 return new OO.ui.RadioOptionWidget( {
15817 label: opt.label !== undefined ? opt.label : optValue
15821 // Restore the previous value, or reset to something sensible
15822 if ( this.radioSelectWidget.getItemFromData( value ) ) {
15823 // Previous value is still available, ensure consistency with the radioSelect
15824 this.setValue( value );
15826 // No longer valid, reset
15827 if ( options.length ) {
15828 this.setValue( options[ 0 ].data );
15836 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
15837 * size of the field as well as its presentation. In addition, these widgets can be configured
15838 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
15839 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
15840 * which modifies incoming values rather than validating them.
15841 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
15843 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15846 * // Example of a text input widget
15847 * var textInput = new OO.ui.TextInputWidget( {
15848 * value: 'Text input'
15850 * $( 'body' ).append( textInput.$element );
15852 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15855 * @extends OO.ui.InputWidget
15856 * @mixins OO.ui.mixin.IconElement
15857 * @mixins OO.ui.mixin.IndicatorElement
15858 * @mixins OO.ui.mixin.PendingElement
15859 * @mixins OO.ui.mixin.LabelElement
15862 * @param {Object} [config] Configuration options
15863 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
15864 * 'email' or 'url'. Ignored if `multiline` is true.
15866 * Some values of `type` result in additional behaviors:
15868 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
15869 * empties the text field
15870 * @cfg {string} [placeholder] Placeholder text
15871 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
15872 * instruct the browser to focus this widget.
15873 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
15874 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
15875 * @cfg {boolean} [multiline=false] Allow multiple lines of text
15876 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
15877 * specifies minimum number of rows to display.
15878 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
15879 * Use the #maxRows config to specify a maximum number of displayed rows.
15880 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
15881 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
15882 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
15883 * the value or placeholder text: `'before'` or `'after'`
15884 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
15885 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
15886 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
15887 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
15888 * (the value must contain only numbers); when RegExp, a regular expression that must match the
15889 * value for it to be considered valid; when Function, a function receiving the value as parameter
15890 * that must return true, or promise resolving to true, for it to be considered valid.
15892 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
15893 // Configuration initialization
15894 config = $.extend( {
15896 labelPosition: 'after'
15898 if ( config.type === 'search' ) {
15899 if ( config.icon === undefined ) {
15900 config.icon = 'search';
15902 // indicator: 'clear' is set dynamically later, depending on value
15904 if ( config.required ) {
15905 if ( config.indicator === undefined ) {
15906 config.indicator = 'required';
15910 // Parent constructor
15911 OO.ui.TextInputWidget.parent.call( this, config );
15913 // Mixin constructors
15914 OO.ui.mixin.IconElement.call( this, config );
15915 OO.ui.mixin.IndicatorElement.call( this, config );
15916 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$input } ) );
15917 OO.ui.mixin.LabelElement.call( this, config );
15920 this.type = this.getSaneType( config );
15921 this.readOnly = false;
15922 this.multiline = !!config.multiline;
15923 this.autosize = !!config.autosize;
15924 this.minRows = config.rows !== undefined ? config.rows : '';
15925 this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 );
15926 this.validate = null;
15927 this.styleHeight = null;
15928 this.scrollWidth = null;
15930 // Clone for resizing
15931 if ( this.autosize ) {
15932 this.$clone = this.$input
15934 .insertAfter( this.$input )
15935 .attr( 'aria-hidden', 'true' )
15936 .addClass( 'oo-ui-element-hidden' );
15939 this.setValidation( config.validate );
15940 this.setLabelPosition( config.labelPosition );
15944 keypress: this.onKeyPress.bind( this ),
15945 blur: this.onBlur.bind( this )
15948 focus: this.onElementAttach.bind( this )
15950 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
15951 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
15952 this.on( 'labelChange', this.updatePosition.bind( this ) );
15953 this.connect( this, {
15954 change: 'onChange',
15955 disable: 'onDisable'
15960 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type )
15961 .append( this.$icon, this.$indicator );
15962 this.setReadOnly( !!config.readOnly );
15963 this.updateSearchIndicator();
15964 if ( config.placeholder ) {
15965 this.$input.attr( 'placeholder', config.placeholder );
15967 if ( config.maxLength !== undefined ) {
15968 this.$input.attr( 'maxlength', config.maxLength );
15970 if ( config.autofocus ) {
15971 this.$input.attr( 'autofocus', 'autofocus' );
15973 if ( config.required ) {
15974 this.$input.attr( 'required', 'required' );
15975 this.$input.attr( 'aria-required', 'true' );
15977 if ( config.autocomplete === false ) {
15978 this.$input.attr( 'autocomplete', 'off' );
15979 // Turning off autocompletion also disables "form caching" when the user navigates to a
15980 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
15982 beforeunload: function () {
15983 this.$input.removeAttr( 'autocomplete' );
15985 pageshow: function () {
15986 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
15987 // whole page... it shouldn't hurt, though.
15988 this.$input.attr( 'autocomplete', 'off' );
15992 if ( this.multiline && config.rows ) {
15993 this.$input.attr( 'rows', config.rows );
15995 if ( this.label || config.autosize ) {
15996 this.installParentChangeDetector();
16002 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
16003 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement );
16004 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement );
16005 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement );
16006 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement );
16008 /* Static Properties */
16010 OO.ui.TextInputWidget.static.validationPatterns = {
16015 /* Static Methods */
16020 OO.ui.TextInputWidget.static.gatherPreInfuseState = function ( node, config ) {
16021 var state = OO.ui.TextInputWidget.parent.static.gatherPreInfuseState( node, config );
16022 if ( config.multiline ) {
16023 state.scrollTop = config.$input.scrollTop();
16031 * An `enter` event is emitted when the user presses 'enter' inside the text box.
16033 * Not emitted if the input is multiline.
16039 * A `resize` event is emitted when autosize is set and the widget resizes
16047 * Handle icon mouse down events.
16050 * @param {jQuery.Event} e Mouse down event
16053 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
16054 if ( e.which === 1 ) {
16055 this.$input[ 0 ].focus();
16061 * Handle indicator mouse down events.
16064 * @param {jQuery.Event} e Mouse down event
16067 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
16068 if ( e.which === 1 ) {
16069 if ( this.type === 'search' ) {
16070 // Clear the text field
16071 this.setValue( '' );
16073 this.$input[ 0 ].focus();
16079 * Handle key press events.
16082 * @param {jQuery.Event} e Key press event
16083 * @fires enter If enter key is pressed and input is not multiline
16085 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
16086 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
16087 this.emit( 'enter', e );
16092 * Handle blur events.
16095 * @param {jQuery.Event} e Blur event
16097 OO.ui.TextInputWidget.prototype.onBlur = function () {
16098 this.setValidityFlag();
16102 * Handle element attach events.
16105 * @param {jQuery.Event} e Element attach event
16107 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
16108 // Any previously calculated size is now probably invalid if we reattached elsewhere
16109 this.valCache = null;
16111 this.positionLabel();
16115 * Handle change events.
16117 * @param {string} value
16120 OO.ui.TextInputWidget.prototype.onChange = function () {
16121 this.updateSearchIndicator();
16122 this.setValidityFlag();
16127 * Handle disable events.
16129 * @param {boolean} disabled Element is disabled
16132 OO.ui.TextInputWidget.prototype.onDisable = function () {
16133 this.updateSearchIndicator();
16137 * Check if the input is {@link #readOnly read-only}.
16139 * @return {boolean}
16141 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
16142 return this.readOnly;
16146 * Set the {@link #readOnly read-only} state of the input.
16148 * @param {boolean} state Make input read-only
16151 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
16152 this.readOnly = !!state;
16153 this.$input.prop( 'readOnly', this.readOnly );
16154 this.updateSearchIndicator();
16159 * Support function for making #onElementAttach work across browsers.
16161 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
16162 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
16164 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
16165 * first time that the element gets attached to the documented.
16167 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
16168 var mutationObserver, onRemove, topmostNode, fakeParentNode,
16169 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
16172 if ( MutationObserver ) {
16173 // The new way. If only it wasn't so ugly.
16175 if ( this.$element.closest( 'html' ).length ) {
16176 // Widget is attached already, do nothing. This breaks the functionality of this function when
16177 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
16178 // would require observation of the whole document, which would hurt performance of other,
16179 // more important code.
16183 // Find topmost node in the tree
16184 topmostNode = this.$element[ 0 ];
16185 while ( topmostNode.parentNode ) {
16186 topmostNode = topmostNode.parentNode;
16189 // We have no way to detect the $element being attached somewhere without observing the entire
16190 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
16191 // parent node of $element, and instead detect when $element is removed from it (and thus
16192 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
16193 // doesn't get attached, we end up back here and create the parent.
16195 mutationObserver = new MutationObserver( function ( mutations ) {
16196 var i, j, removedNodes;
16197 for ( i = 0; i < mutations.length; i++ ) {
16198 removedNodes = mutations[ i ].removedNodes;
16199 for ( j = 0; j < removedNodes.length; j++ ) {
16200 if ( removedNodes[ j ] === topmostNode ) {
16201 setTimeout( onRemove, 0 );
16208 onRemove = function () {
16209 // If the node was attached somewhere else, report it
16210 if ( widget.$element.closest( 'html' ).length ) {
16211 widget.onElementAttach();
16213 mutationObserver.disconnect();
16214 widget.installParentChangeDetector();
16217 // Create a fake parent and observe it
16218 fakeParentNode = $( '<div>' ).append( topmostNode )[ 0 ];
16219 mutationObserver.observe( fakeParentNode, { childList: true } );
16221 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
16222 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
16223 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
16228 * Automatically adjust the size of the text input.
16230 * This only affects #multiline inputs that are {@link #autosize autosized}.
16235 OO.ui.TextInputWidget.prototype.adjustSize = function () {
16236 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError,
16237 idealHeight, newHeight, scrollWidth, property;
16239 if ( this.multiline && this.$input.val() !== this.valCache ) {
16240 if ( this.autosize ) {
16242 .val( this.$input.val() )
16243 .attr( 'rows', this.minRows )
16244 // Set inline height property to 0 to measure scroll height
16245 .css( 'height', 0 );
16247 this.$clone.removeClass( 'oo-ui-element-hidden' );
16249 this.valCache = this.$input.val();
16251 scrollHeight = this.$clone[ 0 ].scrollHeight;
16253 // Remove inline height property to measure natural heights
16254 this.$clone.css( 'height', '' );
16255 innerHeight = this.$clone.innerHeight();
16256 outerHeight = this.$clone.outerHeight();
16258 // Measure max rows height
16260 .attr( 'rows', this.maxRows )
16261 .css( 'height', 'auto' )
16263 maxInnerHeight = this.$clone.innerHeight();
16265 // Difference between reported innerHeight and scrollHeight with no scrollbars present
16266 // Equals 1 on Blink-based browsers and 0 everywhere else
16267 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
16268 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
16270 this.$clone.addClass( 'oo-ui-element-hidden' );
16272 // Only apply inline height when expansion beyond natural height is needed
16273 // Use the difference between the inner and outer height as a buffer
16274 newHeight = idealHeight > innerHeight ? idealHeight + ( outerHeight - innerHeight ) : '';
16275 if ( newHeight !== this.styleHeight ) {
16276 this.$input.css( 'height', newHeight );
16277 this.styleHeight = newHeight;
16278 this.emit( 'resize' );
16281 scrollWidth = this.$input[ 0 ].offsetWidth - this.$input[ 0 ].clientWidth;
16282 if ( scrollWidth !== this.scrollWidth ) {
16283 property = this.$element.css( 'direction' ) === 'rtl' ? 'left' : 'right';
16285 this.$label.css( { right: '', left: '' } );
16286 this.$indicator.css( { right: '', left: '' } );
16288 if ( scrollWidth ) {
16289 this.$indicator.css( property, scrollWidth );
16290 if ( this.labelPosition === 'after' ) {
16291 this.$label.css( property, scrollWidth );
16295 this.scrollWidth = scrollWidth;
16296 this.positionLabel();
16306 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
16307 return config.multiline ?
16308 $( '<textarea>' ) :
16309 $( '<input type="' + this.getSaneType( config ) + '" />' );
16313 * Get sanitized value for 'type' for given config.
16315 * @param {Object} config Configuration options
16316 * @return {string|null}
16319 OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) {
16320 var type = [ 'text', 'password', 'search', 'email', 'url' ].indexOf( config.type ) !== -1 ?
16323 return config.multiline ? 'multiline' : type;
16327 * Check if the input supports multiple lines.
16329 * @return {boolean}
16331 OO.ui.TextInputWidget.prototype.isMultiline = function () {
16332 return !!this.multiline;
16336 * Check if the input automatically adjusts its size.
16338 * @return {boolean}
16340 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
16341 return !!this.autosize;
16345 * Focus the input and select a specified range within the text.
16347 * @param {number} from Select from offset
16348 * @param {number} [to] Select to offset, defaults to from
16351 OO.ui.TextInputWidget.prototype.selectRange = function ( from, to ) {
16352 var textRange, isBackwards, start, end,
16353 input = this.$input[ 0 ];
16357 isBackwards = to < from;
16358 start = isBackwards ? to : from;
16359 end = isBackwards ? from : to;
16363 if ( input.setSelectionRange ) {
16364 input.setSelectionRange( start, end, isBackwards ? 'backward' : 'forward' );
16365 } else if ( input.createTextRange ) {
16367 textRange = input.createTextRange();
16368 textRange.collapse( true );
16369 textRange.moveStart( 'character', start );
16370 textRange.moveEnd( 'character', end - start );
16371 textRange.select();
16377 * Get an object describing the current selection range in a directional manner
16379 * @return {Object} Object containing 'from' and 'to' offsets
16381 OO.ui.TextInputWidget.prototype.getRange = function () {
16382 var input = this.$input[ 0 ],
16383 start = input.selectionStart,
16384 end = input.selectionEnd,
16385 isBackwards = input.selectionDirection === 'backward';
16388 from: isBackwards ? end : start,
16389 to: isBackwards ? start : end
16394 * Get the length of the text input value.
16396 * This could differ from the length of #getValue if the
16397 * value gets filtered
16399 * @return {number} Input length
16401 OO.ui.TextInputWidget.prototype.getInputLength = function () {
16402 return this.$input[ 0 ].value.length;
16406 * Focus the input and select the entire text.
16410 OO.ui.TextInputWidget.prototype.select = function () {
16411 return this.selectRange( 0, this.getInputLength() );
16415 * Focus the input and move the cursor to the start.
16419 OO.ui.TextInputWidget.prototype.moveCursorToStart = function () {
16420 return this.selectRange( 0 );
16424 * Focus the input and move the cursor to the end.
16428 OO.ui.TextInputWidget.prototype.moveCursorToEnd = function () {
16429 return this.selectRange( this.getInputLength() );
16433 * Insert new content into the input.
16435 * @param {string} content Content to be inserted
16438 OO.ui.TextInputWidget.prototype.insertContent = function ( content ) {
16440 range = this.getRange(),
16441 value = this.getValue();
16443 start = Math.min( range.from, range.to );
16444 end = Math.max( range.from, range.to );
16446 this.setValue( value.slice( 0, start ) + content + value.slice( end ) );
16447 this.selectRange( start + content.length );
16452 * Insert new content either side of a selection.
16454 * @param {string} pre Content to be inserted before the selection
16455 * @param {string} post Content to be inserted after the selection
16458 OO.ui.TextInputWidget.prototype.encapsulateContent = function ( pre, post ) {
16460 range = this.getRange(),
16461 offset = pre.length;
16463 start = Math.min( range.from, range.to );
16464 end = Math.max( range.from, range.to );
16466 this.selectRange( start ).insertContent( pre );
16467 this.selectRange( offset + end ).insertContent( post );
16469 this.selectRange( offset + start, offset + end );
16474 * Set the validation pattern.
16476 * The validation pattern is either a regular expression, a function, or the symbolic name of a
16477 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
16478 * value must contain only numbers).
16480 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
16481 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
16483 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
16484 if ( validate instanceof RegExp || validate instanceof Function ) {
16485 this.validate = validate;
16487 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
16492 * Sets the 'invalid' flag appropriately.
16494 * @param {boolean} [isValid] Optionally override validation result
16496 OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) {
16498 setFlag = function ( valid ) {
16500 widget.$input.attr( 'aria-invalid', 'true' );
16502 widget.$input.removeAttr( 'aria-invalid' );
16504 widget.setFlags( { invalid: !valid } );
16507 if ( isValid !== undefined ) {
16508 setFlag( isValid );
16510 this.getValidity().then( function () {
16519 * Check if a value is valid.
16521 * This method returns a promise that resolves with a boolean `true` if the current value is
16522 * considered valid according to the supplied {@link #validate validation pattern}.
16525 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
16527 OO.ui.TextInputWidget.prototype.isValid = function () {
16530 if ( this.validate instanceof Function ) {
16531 result = this.validate( this.getValue() );
16532 if ( $.isFunction( result.promise ) ) {
16533 return result.promise();
16535 return $.Deferred().resolve( !!result ).promise();
16538 return $.Deferred().resolve( !!this.getValue().match( this.validate ) ).promise();
16543 * Get the validity of current value.
16545 * This method returns a promise that resolves if the value is valid and rejects if
16546 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
16548 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
16550 OO.ui.TextInputWidget.prototype.getValidity = function () {
16551 var result, promise;
16553 function rejectOrResolve( valid ) {
16555 return $.Deferred().resolve().promise();
16557 return $.Deferred().reject().promise();
16561 if ( this.validate instanceof Function ) {
16562 result = this.validate( this.getValue() );
16564 if ( $.isFunction( result.promise ) ) {
16565 promise = $.Deferred();
16567 result.then( function ( valid ) {
16577 return promise.promise();
16579 return rejectOrResolve( result );
16582 return rejectOrResolve( this.getValue().match( this.validate ) );
16587 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
16589 * @param {string} labelPosition Label position, 'before' or 'after'
16592 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
16593 this.labelPosition = labelPosition;
16594 this.updatePosition();
16599 * Update the position of the inline label.
16601 * This method is called by #setLabelPosition, and can also be called on its own if
16602 * something causes the label to be mispositioned.
16606 OO.ui.TextInputWidget.prototype.updatePosition = function () {
16607 var after = this.labelPosition === 'after';
16610 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
16611 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
16613 this.valCache = null;
16614 this.scrollWidth = null;
16616 this.positionLabel();
16622 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
16623 * already empty or when it's not editable.
16625 OO.ui.TextInputWidget.prototype.updateSearchIndicator = function () {
16626 if ( this.type === 'search' ) {
16627 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
16628 this.setIndicator( null );
16630 this.setIndicator( 'clear' );
16636 * Position the label by setting the correct padding on the input.
16641 OO.ui.TextInputWidget.prototype.positionLabel = function () {
16642 var after, rtl, property;
16643 // Clear old values
16645 // Clear old values if present
16647 'padding-right': '',
16651 if ( this.label ) {
16652 this.$element.append( this.$label );
16654 this.$label.detach();
16658 after = this.labelPosition === 'after';
16659 rtl = this.$element.css( 'direction' ) === 'rtl';
16660 property = after === rtl ? 'padding-left' : 'padding-right';
16662 this.$input.css( property, this.$label.outerWidth( true ) + ( after ? this.scrollWidth : 0 ) );
16670 OO.ui.TextInputWidget.prototype.restorePreInfuseState = function ( state ) {
16671 OO.ui.TextInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
16672 if ( state.scrollTop !== undefined ) {
16673 this.$input.scrollTop( state.scrollTop );
16678 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
16679 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
16680 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
16682 * - by typing a value in the text input field. If the value exactly matches the value of a menu
16683 * option, that option will appear to be selected.
16684 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
16687 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
16689 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
16692 * // Example: A ComboBoxInputWidget.
16693 * var comboBox = new OO.ui.ComboBoxInputWidget( {
16694 * label: 'ComboBoxInputWidget',
16695 * value: 'Option 1',
16698 * new OO.ui.MenuOptionWidget( {
16699 * data: 'Option 1',
16700 * label: 'Option One'
16702 * new OO.ui.MenuOptionWidget( {
16703 * data: 'Option 2',
16704 * label: 'Option Two'
16706 * new OO.ui.MenuOptionWidget( {
16707 * data: 'Option 3',
16708 * label: 'Option Three'
16710 * new OO.ui.MenuOptionWidget( {
16711 * data: 'Option 4',
16712 * label: 'Option Four'
16714 * new OO.ui.MenuOptionWidget( {
16715 * data: 'Option 5',
16716 * label: 'Option Five'
16721 * $( 'body' ).append( comboBox.$element );
16723 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16726 * @extends OO.ui.TextInputWidget
16729 * @param {Object} [config] Configuration options
16730 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
16731 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
16732 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
16733 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
16734 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
16736 OO.ui.ComboBoxInputWidget = function OoUiComboBoxInputWidget( config ) {
16737 // Configuration initialization
16738 config = $.extend( {
16741 // For backwards-compatibility with ComboBoxWidget config
16742 $.extend( config, config.input );
16744 // Parent constructor
16745 OO.ui.ComboBoxInputWidget.parent.call( this, config );
16748 this.$overlay = config.$overlay || this.$element;
16749 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
16753 $container: this.$element,
16754 disabled: this.isDisabled()
16758 // For backwards-compatibility with ComboBoxWidget
16762 this.$indicator.on( {
16763 click: this.onIndicatorClick.bind( this ),
16764 keypress: this.onIndicatorKeyPress.bind( this )
16766 this.connect( this, {
16767 change: 'onInputChange',
16768 enter: 'onInputEnter'
16770 this.menu.connect( this, {
16771 choose: 'onMenuChoose',
16772 add: 'onMenuItemsChange',
16773 remove: 'onMenuItemsChange'
16777 this.$input.attr( {
16779 'aria-autocomplete': 'list'
16781 // Do not override options set via config.menu.items
16782 if ( config.options !== undefined ) {
16783 this.setOptions( config.options );
16785 // Extra class for backwards-compatibility with ComboBoxWidget
16786 this.$element.addClass( 'oo-ui-comboBoxInputWidget oo-ui-comboBoxWidget' );
16787 this.$overlay.append( this.menu.$element );
16788 this.onMenuItemsChange();
16793 OO.inheritClass( OO.ui.ComboBoxInputWidget, OO.ui.TextInputWidget );
16798 * Get the combobox's menu.
16799 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
16801 OO.ui.ComboBoxInputWidget.prototype.getMenu = function () {
16806 * Get the combobox's text input widget.
16807 * @return {OO.ui.TextInputWidget} Text input widget
16809 OO.ui.ComboBoxInputWidget.prototype.getInput = function () {
16814 * Handle input change events.
16817 * @param {string} value New value
16819 OO.ui.ComboBoxInputWidget.prototype.onInputChange = function ( value ) {
16820 var match = this.menu.getItemFromData( value );
16822 this.menu.selectItem( match );
16823 if ( this.menu.getHighlightedItem() ) {
16824 this.menu.highlightItem( match );
16827 if ( !this.isDisabled() ) {
16828 this.menu.toggle( true );
16833 * Handle mouse click events.
16836 * @param {jQuery.Event} e Mouse click event
16838 OO.ui.ComboBoxInputWidget.prototype.onIndicatorClick = function ( e ) {
16839 if ( !this.isDisabled() && e.which === 1 ) {
16840 this.menu.toggle();
16841 this.$input[ 0 ].focus();
16847 * Handle key press events.
16850 * @param {jQuery.Event} e Key press event
16852 OO.ui.ComboBoxInputWidget.prototype.onIndicatorKeyPress = function ( e ) {
16853 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
16854 this.menu.toggle();
16855 this.$input[ 0 ].focus();
16861 * Handle input enter events.
16865 OO.ui.ComboBoxInputWidget.prototype.onInputEnter = function () {
16866 if ( !this.isDisabled() ) {
16867 this.menu.toggle( false );
16872 * Handle menu choose events.
16875 * @param {OO.ui.OptionWidget} item Chosen item
16877 OO.ui.ComboBoxInputWidget.prototype.onMenuChoose = function ( item ) {
16878 this.setValue( item.getData() );
16882 * Handle menu item change events.
16886 OO.ui.ComboBoxInputWidget.prototype.onMenuItemsChange = function () {
16887 var match = this.menu.getItemFromData( this.getValue() );
16888 this.menu.selectItem( match );
16889 if ( this.menu.getHighlightedItem() ) {
16890 this.menu.highlightItem( match );
16892 this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu.isEmpty() );
16898 OO.ui.ComboBoxInputWidget.prototype.setDisabled = function ( disabled ) {
16900 OO.ui.ComboBoxInputWidget.parent.prototype.setDisabled.call( this, disabled );
16903 this.menu.setDisabled( this.isDisabled() );
16910 * Set the options available for this input.
16912 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
16915 OO.ui.ComboBoxInputWidget.prototype.setOptions = function ( options ) {
16918 .addItems( options.map( function ( opt ) {
16919 return new OO.ui.MenuOptionWidget( {
16921 label: opt.label !== undefined ? opt.label : opt.data
16930 * @deprecated Use OO.ui.ComboBoxInputWidget instead.
16932 OO.ui.ComboBoxWidget = OO.ui.ComboBoxInputWidget;
16935 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
16936 * be configured with a `label` option that is set to a string, a label node, or a function:
16938 * - String: a plaintext string
16939 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
16940 * label that includes a link or special styling, such as a gray color or additional graphical elements.
16941 * - Function: a function that will produce a string in the future. Functions are used
16942 * in cases where the value of the label is not currently defined.
16944 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
16945 * will come into focus when the label is clicked.
16948 * // Examples of LabelWidgets
16949 * var label1 = new OO.ui.LabelWidget( {
16950 * label: 'plaintext label'
16952 * var label2 = new OO.ui.LabelWidget( {
16953 * label: $( '<a href="default.html">jQuery label</a>' )
16955 * // Create a fieldset layout with fields for each example
16956 * var fieldset = new OO.ui.FieldsetLayout();
16957 * fieldset.addItems( [
16958 * new OO.ui.FieldLayout( label1 ),
16959 * new OO.ui.FieldLayout( label2 )
16961 * $( 'body' ).append( fieldset.$element );
16964 * @extends OO.ui.Widget
16965 * @mixins OO.ui.mixin.LabelElement
16968 * @param {Object} [config] Configuration options
16969 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
16970 * Clicking the label will focus the specified input field.
16972 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
16973 // Configuration initialization
16974 config = config || {};
16976 // Parent constructor
16977 OO.ui.LabelWidget.parent.call( this, config );
16979 // Mixin constructors
16980 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
16981 OO.ui.mixin.TitledElement.call( this, config );
16984 this.input = config.input;
16987 if ( this.input instanceof OO.ui.InputWidget ) {
16988 this.$element.on( 'click', this.onClick.bind( this ) );
16992 this.$element.addClass( 'oo-ui-labelWidget' );
16997 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
16998 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.LabelElement );
16999 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.TitledElement );
17001 /* Static Properties */
17003 OO.ui.LabelWidget.static.tagName = 'span';
17008 * Handles label mouse click events.
17011 * @param {jQuery.Event} e Mouse click event
17013 OO.ui.LabelWidget.prototype.onClick = function () {
17014 this.input.simulateLabelClick();
17019 * OptionWidgets are special elements that can be selected and configured with data. The
17020 * data is often unique for each option, but it does not have to be. OptionWidgets are used
17021 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
17022 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
17024 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17027 * @extends OO.ui.Widget
17028 * @mixins OO.ui.mixin.LabelElement
17029 * @mixins OO.ui.mixin.FlaggedElement
17032 * @param {Object} [config] Configuration options
17034 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
17035 // Configuration initialization
17036 config = config || {};
17038 // Parent constructor
17039 OO.ui.OptionWidget.parent.call( this, config );
17041 // Mixin constructors
17042 OO.ui.mixin.ItemWidget.call( this );
17043 OO.ui.mixin.LabelElement.call( this, config );
17044 OO.ui.mixin.FlaggedElement.call( this, config );
17047 this.selected = false;
17048 this.highlighted = false;
17049 this.pressed = false;
17053 .data( 'oo-ui-optionWidget', this )
17054 .attr( 'role', 'option' )
17055 .attr( 'aria-selected', 'false' )
17056 .addClass( 'oo-ui-optionWidget' )
17057 .append( this.$label );
17062 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
17063 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.ItemWidget );
17064 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.LabelElement );
17065 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.FlaggedElement );
17067 /* Static Properties */
17069 OO.ui.OptionWidget.static.selectable = true;
17071 OO.ui.OptionWidget.static.highlightable = true;
17073 OO.ui.OptionWidget.static.pressable = true;
17075 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
17080 * Check if the option can be selected.
17082 * @return {boolean} Item is selectable
17084 OO.ui.OptionWidget.prototype.isSelectable = function () {
17085 return this.constructor.static.selectable && !this.isDisabled() && this.isVisible();
17089 * Check if the option can be highlighted. A highlight indicates that the option
17090 * may be selected when a user presses enter or clicks. Disabled items cannot
17093 * @return {boolean} Item is highlightable
17095 OO.ui.OptionWidget.prototype.isHighlightable = function () {
17096 return this.constructor.static.highlightable && !this.isDisabled() && this.isVisible();
17100 * Check if the option can be pressed. The pressed state occurs when a user mouses
17101 * down on an item, but has not yet let go of the mouse.
17103 * @return {boolean} Item is pressable
17105 OO.ui.OptionWidget.prototype.isPressable = function () {
17106 return this.constructor.static.pressable && !this.isDisabled() && this.isVisible();
17110 * Check if the option is selected.
17112 * @return {boolean} Item is selected
17114 OO.ui.OptionWidget.prototype.isSelected = function () {
17115 return this.selected;
17119 * Check if the option is highlighted. A highlight indicates that the
17120 * item may be selected when a user presses enter or clicks.
17122 * @return {boolean} Item is highlighted
17124 OO.ui.OptionWidget.prototype.isHighlighted = function () {
17125 return this.highlighted;
17129 * Check if the option is pressed. The pressed state occurs when a user mouses
17130 * down on an item, but has not yet let go of the mouse. The item may appear
17131 * selected, but it will not be selected until the user releases the mouse.
17133 * @return {boolean} Item is pressed
17135 OO.ui.OptionWidget.prototype.isPressed = function () {
17136 return this.pressed;
17140 * Set the option’s selected state. In general, all modifications to the selection
17141 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
17142 * method instead of this method.
17144 * @param {boolean} [state=false] Select option
17147 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
17148 if ( this.constructor.static.selectable ) {
17149 this.selected = !!state;
17151 .toggleClass( 'oo-ui-optionWidget-selected', state )
17152 .attr( 'aria-selected', state.toString() );
17153 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
17154 this.scrollElementIntoView();
17156 this.updateThemeClasses();
17162 * Set the option’s highlighted state. In general, all programmatic
17163 * modifications to the highlight should be handled by the
17164 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
17165 * method instead of this method.
17167 * @param {boolean} [state=false] Highlight option
17170 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
17171 if ( this.constructor.static.highlightable ) {
17172 this.highlighted = !!state;
17173 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
17174 this.updateThemeClasses();
17180 * Set the option’s pressed state. In general, all
17181 * programmatic modifications to the pressed state should be handled by the
17182 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
17183 * method instead of this method.
17185 * @param {boolean} [state=false] Press option
17188 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
17189 if ( this.constructor.static.pressable ) {
17190 this.pressed = !!state;
17191 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
17192 this.updateThemeClasses();
17198 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
17199 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
17200 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
17201 * options. For more information about options and selects, please see the
17202 * [OOjs UI documentation on MediaWiki][1].
17205 * // Decorated options in a select widget
17206 * var select = new OO.ui.SelectWidget( {
17208 * new OO.ui.DecoratedOptionWidget( {
17210 * label: 'Option with icon',
17213 * new OO.ui.DecoratedOptionWidget( {
17215 * label: 'Option with indicator',
17216 * indicator: 'next'
17220 * $( 'body' ).append( select.$element );
17222 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17225 * @extends OO.ui.OptionWidget
17226 * @mixins OO.ui.mixin.IconElement
17227 * @mixins OO.ui.mixin.IndicatorElement
17230 * @param {Object} [config] Configuration options
17232 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
17233 // Parent constructor
17234 OO.ui.DecoratedOptionWidget.parent.call( this, config );
17236 // Mixin constructors
17237 OO.ui.mixin.IconElement.call( this, config );
17238 OO.ui.mixin.IndicatorElement.call( this, config );
17242 .addClass( 'oo-ui-decoratedOptionWidget' )
17243 .prepend( this.$icon )
17244 .append( this.$indicator );
17249 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
17250 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IconElement );
17251 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IndicatorElement );
17254 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
17255 * can be selected and configured with data. The class is
17256 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
17257 * [OOjs UI documentation on MediaWiki] [1] for more information.
17259 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
17262 * @extends OO.ui.DecoratedOptionWidget
17263 * @mixins OO.ui.mixin.ButtonElement
17264 * @mixins OO.ui.mixin.TabIndexedElement
17265 * @mixins OO.ui.mixin.TitledElement
17268 * @param {Object} [config] Configuration options
17270 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
17271 // Configuration initialization
17272 config = config || {};
17274 // Parent constructor
17275 OO.ui.ButtonOptionWidget.parent.call( this, config );
17277 // Mixin constructors
17278 OO.ui.mixin.ButtonElement.call( this, config );
17279 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
17280 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, {
17281 $tabIndexed: this.$button,
17286 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
17287 this.$button.append( this.$element.contents() );
17288 this.$element.append( this.$button );
17293 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.DecoratedOptionWidget );
17294 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.ButtonElement );
17295 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TitledElement );
17296 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TabIndexedElement );
17298 /* Static Properties */
17300 // Allow button mouse down events to pass through so they can be handled by the parent select widget
17301 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
17303 OO.ui.ButtonOptionWidget.static.highlightable = false;
17310 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
17311 OO.ui.ButtonOptionWidget.parent.prototype.setSelected.call( this, state );
17313 if ( this.constructor.static.selectable ) {
17314 this.setActive( state );
17321 * RadioOptionWidget is an option widget that looks like a radio button.
17322 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
17323 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
17325 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
17328 * @extends OO.ui.OptionWidget
17331 * @param {Object} [config] Configuration options
17333 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
17334 // Configuration initialization
17335 config = config || {};
17337 // Properties (must be done before parent constructor which calls #setDisabled)
17338 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
17340 // Parent constructor
17341 OO.ui.RadioOptionWidget.parent.call( this, config );
17344 this.radio.$input.on( 'focus', this.onInputFocus.bind( this ) );
17347 // Remove implicit role, we're handling it ourselves
17348 this.radio.$input.attr( 'role', 'presentation' );
17350 .addClass( 'oo-ui-radioOptionWidget' )
17351 .attr( 'role', 'radio' )
17352 .attr( 'aria-checked', 'false' )
17353 .removeAttr( 'aria-selected' )
17354 .prepend( this.radio.$element );
17359 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
17361 /* Static Properties */
17363 OO.ui.RadioOptionWidget.static.highlightable = false;
17365 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
17367 OO.ui.RadioOptionWidget.static.pressable = false;
17369 OO.ui.RadioOptionWidget.static.tagName = 'label';
17374 * @param {jQuery.Event} e Focus event
17377 OO.ui.RadioOptionWidget.prototype.onInputFocus = function () {
17378 this.radio.$input.blur();
17379 this.$element.parent().focus();
17385 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
17386 OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state );
17388 this.radio.setSelected( state );
17390 .attr( 'aria-checked', state.toString() )
17391 .removeAttr( 'aria-selected' );
17399 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
17400 OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled );
17402 this.radio.setDisabled( this.isDisabled() );
17408 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
17409 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
17410 * the [OOjs UI documentation on MediaWiki] [1] for more information.
17412 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
17415 * @extends OO.ui.DecoratedOptionWidget
17418 * @param {Object} [config] Configuration options
17420 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
17421 // Configuration initialization
17422 config = $.extend( { icon: 'check' }, config );
17424 // Parent constructor
17425 OO.ui.MenuOptionWidget.parent.call( this, config );
17429 .attr( 'role', 'menuitem' )
17430 .addClass( 'oo-ui-menuOptionWidget' );
17435 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
17437 /* Static Properties */
17439 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
17442 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
17443 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
17446 * var myDropdown = new OO.ui.DropdownWidget( {
17449 * new OO.ui.MenuSectionOptionWidget( {
17452 * new OO.ui.MenuOptionWidget( {
17454 * label: 'Welsh Corgi'
17456 * new OO.ui.MenuOptionWidget( {
17458 * label: 'Standard Poodle'
17460 * new OO.ui.MenuSectionOptionWidget( {
17463 * new OO.ui.MenuOptionWidget( {
17470 * $( 'body' ).append( myDropdown.$element );
17473 * @extends OO.ui.DecoratedOptionWidget
17476 * @param {Object} [config] Configuration options
17478 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
17479 // Parent constructor
17480 OO.ui.MenuSectionOptionWidget.parent.call( this, config );
17483 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' );
17488 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
17490 /* Static Properties */
17492 OO.ui.MenuSectionOptionWidget.static.selectable = false;
17494 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
17497 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
17499 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
17500 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
17504 * @extends OO.ui.DecoratedOptionWidget
17507 * @param {Object} [config] Configuration options
17508 * @cfg {number} [level] Indentation level
17509 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
17511 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
17512 // Configuration initialization
17513 config = config || {};
17515 // Parent constructor
17516 OO.ui.OutlineOptionWidget.parent.call( this, config );
17520 this.movable = !!config.movable;
17521 this.removable = !!config.removable;
17524 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
17525 this.setLevel( config.level );
17530 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
17532 /* Static Properties */
17534 OO.ui.OutlineOptionWidget.static.highlightable = false;
17536 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
17538 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
17540 OO.ui.OutlineOptionWidget.static.levels = 3;
17545 * Check if item is movable.
17547 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17549 * @return {boolean} Item is movable
17551 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
17552 return this.movable;
17556 * Check if item is removable.
17558 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17560 * @return {boolean} Item is removable
17562 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
17563 return this.removable;
17567 * Get indentation level.
17569 * @return {number} Indentation level
17571 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
17578 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17580 * @param {boolean} movable Item is movable
17583 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
17584 this.movable = !!movable;
17585 this.updateThemeClasses();
17590 * Set removability.
17592 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17594 * @param {boolean} movable Item is removable
17597 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
17598 this.removable = !!removable;
17599 this.updateThemeClasses();
17604 * Set indentation level.
17606 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
17609 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
17610 var levels = this.constructor.static.levels,
17611 levelClass = this.constructor.static.levelClass,
17614 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
17616 if ( this.level === i ) {
17617 this.$element.addClass( levelClass + i );
17619 this.$element.removeClass( levelClass + i );
17622 this.updateThemeClasses();
17628 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
17630 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
17631 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
17635 * @extends OO.ui.OptionWidget
17638 * @param {Object} [config] Configuration options
17640 OO.ui.TabOptionWidget = function OoUiTabOptionWidget( config ) {
17641 // Configuration initialization
17642 config = config || {};
17644 // Parent constructor
17645 OO.ui.TabOptionWidget.parent.call( this, config );
17648 this.$element.addClass( 'oo-ui-tabOptionWidget' );
17653 OO.inheritClass( OO.ui.TabOptionWidget, OO.ui.OptionWidget );
17655 /* Static Properties */
17657 OO.ui.TabOptionWidget.static.highlightable = false;
17660 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
17661 * By default, each popup has an anchor that points toward its origin.
17662 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
17665 * // A popup widget.
17666 * var popup = new OO.ui.PopupWidget( {
17667 * $content: $( '<p>Hi there!</p>' ),
17672 * $( 'body' ).append( popup.$element );
17673 * // To display the popup, toggle the visibility to 'true'.
17674 * popup.toggle( true );
17676 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
17679 * @extends OO.ui.Widget
17680 * @mixins OO.ui.mixin.LabelElement
17681 * @mixins OO.ui.mixin.ClippableElement
17684 * @param {Object} [config] Configuration options
17685 * @cfg {number} [width=320] Width of popup in pixels
17686 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
17687 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
17688 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
17689 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
17690 * popup is leaning towards the right of the screen.
17691 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
17692 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
17693 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
17694 * sentence in the given language.
17695 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
17696 * See the [OOjs UI docs on MediaWiki][3] for an example.
17697 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
17698 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
17699 * @cfg {jQuery} [$content] Content to append to the popup's body
17700 * @cfg {jQuery} [$footer] Content to append to the popup's footer
17701 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
17702 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
17703 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
17705 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
17706 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
17708 * @cfg {boolean} [padded] Add padding to the popup's body
17710 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
17711 // Configuration initialization
17712 config = config || {};
17714 // Parent constructor
17715 OO.ui.PopupWidget.parent.call( this, config );
17717 // Properties (must be set before ClippableElement constructor call)
17718 this.$body = $( '<div>' );
17719 this.$popup = $( '<div>' );
17721 // Mixin constructors
17722 OO.ui.mixin.LabelElement.call( this, config );
17723 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, {
17724 $clippable: this.$body,
17725 $clippableContainer: this.$popup
17729 this.$head = $( '<div>' );
17730 this.$footer = $( '<div>' );
17731 this.$anchor = $( '<div>' );
17732 // If undefined, will be computed lazily in updateDimensions()
17733 this.$container = config.$container;
17734 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
17735 this.autoClose = !!config.autoClose;
17736 this.$autoCloseIgnore = config.$autoCloseIgnore;
17737 this.transitionTimeout = null;
17738 this.anchor = null;
17739 this.width = config.width !== undefined ? config.width : 320;
17740 this.height = config.height !== undefined ? config.height : null;
17741 this.setAlignment( config.align );
17742 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
17743 this.onMouseDownHandler = this.onMouseDown.bind( this );
17744 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
17747 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
17750 this.toggleAnchor( config.anchor === undefined || config.anchor );
17751 this.$body.addClass( 'oo-ui-popupWidget-body' );
17752 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
17754 .addClass( 'oo-ui-popupWidget-head' )
17755 .append( this.$label, this.closeButton.$element );
17756 this.$footer.addClass( 'oo-ui-popupWidget-footer' );
17757 if ( !config.head ) {
17758 this.$head.addClass( 'oo-ui-element-hidden' );
17760 if ( !config.$footer ) {
17761 this.$footer.addClass( 'oo-ui-element-hidden' );
17764 .addClass( 'oo-ui-popupWidget-popup' )
17765 .append( this.$head, this.$body, this.$footer );
17767 .addClass( 'oo-ui-popupWidget' )
17768 .append( this.$popup, this.$anchor );
17769 // Move content, which was added to #$element by OO.ui.Widget, to the body
17770 if ( config.$content instanceof jQuery ) {
17771 this.$body.append( config.$content );
17773 if ( config.$footer instanceof jQuery ) {
17774 this.$footer.append( config.$footer );
17776 if ( config.padded ) {
17777 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
17780 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
17781 // that reference properties not initialized at that time of parent class construction
17782 // TODO: Find a better way to handle post-constructor setup
17783 this.visible = false;
17784 this.$element.addClass( 'oo-ui-element-hidden' );
17789 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
17790 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.LabelElement );
17791 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.ClippableElement );
17796 * Handles mouse down events.
17799 * @param {MouseEvent} e Mouse down event
17801 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
17803 this.isVisible() &&
17804 !$.contains( this.$element[ 0 ], e.target ) &&
17805 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
17807 this.toggle( false );
17812 * Bind mouse down listener.
17816 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
17817 // Capture clicks outside popup
17818 OO.ui.addCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler );
17822 * Handles close button click events.
17826 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
17827 if ( this.isVisible() ) {
17828 this.toggle( false );
17833 * Unbind mouse down listener.
17837 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
17838 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler );
17842 * Handles key down events.
17845 * @param {KeyboardEvent} e Key down event
17847 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
17849 e.which === OO.ui.Keys.ESCAPE &&
17852 this.toggle( false );
17853 e.preventDefault();
17854 e.stopPropagation();
17859 * Bind key down listener.
17863 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
17864 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler );
17868 * Unbind key down listener.
17872 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
17873 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler );
17877 * Show, hide, or toggle the visibility of the anchor.
17879 * @param {boolean} [show] Show anchor, omit to toggle
17881 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
17882 show = show === undefined ? !this.anchored : !!show;
17884 if ( this.anchored !== show ) {
17886 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
17888 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
17890 this.anchored = show;
17895 * Check if the anchor is visible.
17897 * @return {boolean} Anchor is visible
17899 OO.ui.PopupWidget.prototype.hasAnchor = function () {
17900 return this.anchor;
17906 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
17908 show = show === undefined ? !this.isVisible() : !!show;
17910 change = show !== this.isVisible();
17913 OO.ui.PopupWidget.parent.prototype.toggle.call( this, show );
17917 if ( this.autoClose ) {
17918 this.bindMouseDownListener();
17919 this.bindKeyDownListener();
17921 this.updateDimensions();
17922 this.toggleClipping( true );
17924 this.toggleClipping( false );
17925 if ( this.autoClose ) {
17926 this.unbindMouseDownListener();
17927 this.unbindKeyDownListener();
17936 * Set the size of the popup.
17938 * Changing the size may also change the popup's position depending on the alignment.
17940 * @param {number} width Width in pixels
17941 * @param {number} height Height in pixels
17942 * @param {boolean} [transition=false] Use a smooth transition
17945 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
17946 this.width = width;
17947 this.height = height !== undefined ? height : null;
17948 if ( this.isVisible() ) {
17949 this.updateDimensions( transition );
17954 * Update the size and position.
17956 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
17957 * be called automatically.
17959 * @param {boolean} [transition=false] Use a smooth transition
17962 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
17963 var popupOffset, originOffset, containerLeft, containerWidth, containerRight,
17964 popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth,
17965 align = this.align,
17968 if ( !this.$container ) {
17969 // Lazy-initialize $container if not specified in constructor
17970 this.$container = $( this.getClosestScrollableElementContainer() );
17973 // Set height and width before measuring things, since it might cause our measurements
17974 // to change (e.g. due to scrollbars appearing or disappearing)
17977 height: this.height !== null ? this.height : 'auto'
17980 // If we are in RTL, we need to flip the alignment, unless it is center
17981 if ( align === 'forwards' || align === 'backwards' ) {
17982 if ( this.$container.css( 'direction' ) === 'rtl' ) {
17983 align = ( { forwards: 'force-left', backwards: 'force-right' } )[ this.align ];
17985 align = ( { forwards: 'force-right', backwards: 'force-left' } )[ this.align ];
17990 // Compute initial popupOffset based on alignment
17991 popupOffset = this.width * ( { 'force-left': -1, center: -0.5, 'force-right': 0 } )[ align ];
17993 // Figure out if this will cause the popup to go beyond the edge of the container
17994 originOffset = this.$element.offset().left;
17995 containerLeft = this.$container.offset().left;
17996 containerWidth = this.$container.innerWidth();
17997 containerRight = containerLeft + containerWidth;
17998 popupLeft = popupOffset - this.containerPadding;
17999 popupRight = popupOffset + this.containerPadding + this.width + this.containerPadding;
18000 overlapLeft = ( originOffset + popupLeft ) - containerLeft;
18001 overlapRight = containerRight - ( originOffset + popupRight );
18003 // Adjust offset to make the popup not go beyond the edge, if needed
18004 if ( overlapRight < 0 ) {
18005 popupOffset += overlapRight;
18006 } else if ( overlapLeft < 0 ) {
18007 popupOffset -= overlapLeft;
18010 // Adjust offset to avoid anchor being rendered too close to the edge
18011 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
18012 // TODO: Find a measurement that works for CSS anchors and image anchors
18013 anchorWidth = this.$anchor[ 0 ].scrollWidth * 2;
18014 if ( popupOffset + this.width < anchorWidth ) {
18015 popupOffset = anchorWidth - this.width;
18016 } else if ( -popupOffset < anchorWidth ) {
18017 popupOffset = -anchorWidth;
18020 // Prevent transition from being interrupted
18021 clearTimeout( this.transitionTimeout );
18022 if ( transition ) {
18023 // Enable transition
18024 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
18027 // Position body relative to anchor
18028 this.$popup.css( 'margin-left', popupOffset );
18030 if ( transition ) {
18031 // Prevent transitioning after transition is complete
18032 this.transitionTimeout = setTimeout( function () {
18033 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
18036 // Prevent transitioning immediately
18037 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
18040 // Reevaluate clipping state since we've relocated and resized the popup
18047 * Set popup alignment
18048 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
18049 * `backwards` or `forwards`.
18051 OO.ui.PopupWidget.prototype.setAlignment = function ( align ) {
18052 // Validate alignment and transform deprecated values
18053 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) {
18054 this.align = { left: 'force-right', right: 'force-left' }[ align ] || align;
18056 this.align = 'center';
18061 * Get popup alignment
18062 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
18063 * `backwards` or `forwards`.
18065 OO.ui.PopupWidget.prototype.getAlignment = function () {
18070 * Progress bars visually display the status of an operation, such as a download,
18071 * and can be either determinate or indeterminate:
18073 * - **determinate** process bars show the percent of an operation that is complete.
18075 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
18076 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
18077 * not use percentages.
18079 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
18082 * // Examples of determinate and indeterminate progress bars.
18083 * var progressBar1 = new OO.ui.ProgressBarWidget( {
18086 * var progressBar2 = new OO.ui.ProgressBarWidget();
18088 * // Create a FieldsetLayout to layout progress bars
18089 * var fieldset = new OO.ui.FieldsetLayout;
18090 * fieldset.addItems( [
18091 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
18092 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
18094 * $( 'body' ).append( fieldset.$element );
18097 * @extends OO.ui.Widget
18100 * @param {Object} [config] Configuration options
18101 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
18102 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
18103 * By default, the progress bar is indeterminate.
18105 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
18106 // Configuration initialization
18107 config = config || {};
18109 // Parent constructor
18110 OO.ui.ProgressBarWidget.parent.call( this, config );
18113 this.$bar = $( '<div>' );
18114 this.progress = null;
18117 this.setProgress( config.progress !== undefined ? config.progress : false );
18118 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
18121 role: 'progressbar',
18122 'aria-valuemin': 0,
18123 'aria-valuemax': 100
18125 .addClass( 'oo-ui-progressBarWidget' )
18126 .append( this.$bar );
18131 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
18133 /* Static Properties */
18135 OO.ui.ProgressBarWidget.static.tagName = 'div';
18140 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
18142 * @return {number|boolean} Progress percent
18144 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
18145 return this.progress;
18149 * Set the percent of the process completed or `false` for an indeterminate process.
18151 * @param {number|boolean} progress Progress percent or `false` for indeterminate
18153 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
18154 this.progress = progress;
18156 if ( progress !== false ) {
18157 this.$bar.css( 'width', this.progress + '%' );
18158 this.$element.attr( 'aria-valuenow', this.progress );
18160 this.$bar.css( 'width', '' );
18161 this.$element.removeAttr( 'aria-valuenow' );
18163 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress );
18167 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
18168 * and a menu of search results, which is displayed beneath the query
18169 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
18170 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
18171 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
18173 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
18174 * the [OOjs UI demos][1] for an example.
18176 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
18179 * @extends OO.ui.Widget
18182 * @param {Object} [config] Configuration options
18183 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
18184 * @cfg {string} [value] Initial query value
18186 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
18187 // Configuration initialization
18188 config = config || {};
18190 // Parent constructor
18191 OO.ui.SearchWidget.parent.call( this, config );
18194 this.query = new OO.ui.TextInputWidget( {
18196 placeholder: config.placeholder,
18197 value: config.value
18199 this.results = new OO.ui.SelectWidget();
18200 this.$query = $( '<div>' );
18201 this.$results = $( '<div>' );
18204 this.query.connect( this, {
18205 change: 'onQueryChange',
18206 enter: 'onQueryEnter'
18208 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
18212 .addClass( 'oo-ui-searchWidget-query' )
18213 .append( this.query.$element );
18215 .addClass( 'oo-ui-searchWidget-results' )
18216 .append( this.results.$element );
18218 .addClass( 'oo-ui-searchWidget' )
18219 .append( this.$results, this.$query );
18224 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
18229 * Handle query key down events.
18232 * @param {jQuery.Event} e Key down event
18234 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
18235 var highlightedItem, nextItem,
18236 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
18239 highlightedItem = this.results.getHighlightedItem();
18240 if ( !highlightedItem ) {
18241 highlightedItem = this.results.getSelectedItem();
18243 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
18244 this.results.highlightItem( nextItem );
18245 nextItem.scrollElementIntoView();
18250 * Handle select widget select events.
18252 * Clears existing results. Subclasses should repopulate items according to new query.
18255 * @param {string} value New value
18257 OO.ui.SearchWidget.prototype.onQueryChange = function () {
18259 this.results.clearItems();
18263 * Handle select widget enter key events.
18265 * Chooses highlighted item.
18268 * @param {string} value New value
18270 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
18271 var highlightedItem = this.results.getHighlightedItem();
18272 if ( highlightedItem ) {
18273 this.results.chooseItem( highlightedItem );
18278 * Get the query input.
18280 * @return {OO.ui.TextInputWidget} Query input
18282 OO.ui.SearchWidget.prototype.getQuery = function () {
18287 * Get the search results menu.
18289 * @return {OO.ui.SelectWidget} Menu of search results
18291 OO.ui.SearchWidget.prototype.getResults = function () {
18292 return this.results;
18296 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
18297 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
18298 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
18301 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
18302 * information, please see the [OOjs UI documentation on MediaWiki][1].
18305 * // Example of a select widget with three options
18306 * var select = new OO.ui.SelectWidget( {
18308 * new OO.ui.OptionWidget( {
18310 * label: 'Option One',
18312 * new OO.ui.OptionWidget( {
18314 * label: 'Option Two',
18316 * new OO.ui.OptionWidget( {
18318 * label: 'Option Three',
18322 * $( 'body' ).append( select.$element );
18324 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18328 * @extends OO.ui.Widget
18329 * @mixins OO.ui.mixin.GroupWidget
18332 * @param {Object} [config] Configuration options
18333 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
18334 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
18335 * the [OOjs UI documentation on MediaWiki] [2] for examples.
18336 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18338 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
18339 // Configuration initialization
18340 config = config || {};
18342 // Parent constructor
18343 OO.ui.SelectWidget.parent.call( this, config );
18345 // Mixin constructors
18346 OO.ui.mixin.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
18349 this.pressed = false;
18350 this.selecting = null;
18351 this.onMouseUpHandler = this.onMouseUp.bind( this );
18352 this.onMouseMoveHandler = this.onMouseMove.bind( this );
18353 this.onKeyDownHandler = this.onKeyDown.bind( this );
18354 this.onKeyPressHandler = this.onKeyPress.bind( this );
18355 this.keyPressBuffer = '';
18356 this.keyPressBufferTimer = null;
18359 this.connect( this, {
18362 this.$element.on( {
18363 mousedown: this.onMouseDown.bind( this ),
18364 mouseover: this.onMouseOver.bind( this ),
18365 mouseleave: this.onMouseLeave.bind( this )
18370 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
18371 .attr( 'role', 'listbox' );
18372 if ( Array.isArray( config.items ) ) {
18373 this.addItems( config.items );
18379 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
18381 // Need to mixin base class as well
18382 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupElement );
18383 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupWidget );
18386 OO.ui.SelectWidget.static.passAllFilter = function () {
18395 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
18397 * @param {OO.ui.OptionWidget|null} item Highlighted item
18403 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
18404 * pressed state of an option.
18406 * @param {OO.ui.OptionWidget|null} item Pressed item
18412 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
18414 * @param {OO.ui.OptionWidget|null} item Selected item
18419 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
18420 * @param {OO.ui.OptionWidget} item Chosen item
18426 * An `add` event is emitted when options are added to the select with the #addItems method.
18428 * @param {OO.ui.OptionWidget[]} items Added items
18429 * @param {number} index Index of insertion point
18435 * A `remove` event is emitted when options are removed from the select with the #clearItems
18436 * or #removeItems methods.
18438 * @param {OO.ui.OptionWidget[]} items Removed items
18444 * Handle mouse down events.
18447 * @param {jQuery.Event} e Mouse down event
18449 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
18452 if ( !this.isDisabled() && e.which === 1 ) {
18453 this.togglePressed( true );
18454 item = this.getTargetItem( e );
18455 if ( item && item.isSelectable() ) {
18456 this.pressItem( item );
18457 this.selecting = item;
18458 OO.ui.addCaptureEventListener(
18459 this.getElementDocument(),
18461 this.onMouseUpHandler
18463 OO.ui.addCaptureEventListener(
18464 this.getElementDocument(),
18466 this.onMouseMoveHandler
18474 * Handle mouse up events.
18477 * @param {jQuery.Event} e Mouse up event
18479 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
18482 this.togglePressed( false );
18483 if ( !this.selecting ) {
18484 item = this.getTargetItem( e );
18485 if ( item && item.isSelectable() ) {
18486 this.selecting = item;
18489 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
18490 this.pressItem( null );
18491 this.chooseItem( this.selecting );
18492 this.selecting = null;
18495 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup',
18496 this.onMouseUpHandler );
18497 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mousemove',
18498 this.onMouseMoveHandler );
18504 * Handle mouse move events.
18507 * @param {jQuery.Event} e Mouse move event
18509 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
18512 if ( !this.isDisabled() && this.pressed ) {
18513 item = this.getTargetItem( e );
18514 if ( item && item !== this.selecting && item.isSelectable() ) {
18515 this.pressItem( item );
18516 this.selecting = item;
18523 * Handle mouse over events.
18526 * @param {jQuery.Event} e Mouse over event
18528 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
18531 if ( !this.isDisabled() ) {
18532 item = this.getTargetItem( e );
18533 this.highlightItem( item && item.isHighlightable() ? item : null );
18539 * Handle mouse leave events.
18542 * @param {jQuery.Event} e Mouse over event
18544 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
18545 if ( !this.isDisabled() ) {
18546 this.highlightItem( null );
18552 * Handle key down events.
18555 * @param {jQuery.Event} e Key down event
18557 OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) {
18560 currentItem = this.getHighlightedItem() || this.getSelectedItem();
18562 if ( !this.isDisabled() && this.isVisible() ) {
18563 switch ( e.keyCode ) {
18564 case OO.ui.Keys.ENTER:
18565 if ( currentItem && currentItem.constructor.static.highlightable ) {
18566 // Was only highlighted, now let's select it. No-op if already selected.
18567 this.chooseItem( currentItem );
18571 case OO.ui.Keys.UP:
18572 case OO.ui.Keys.LEFT:
18573 this.clearKeyPressBuffer();
18574 nextItem = this.getRelativeSelectableItem( currentItem, -1 );
18577 case OO.ui.Keys.DOWN:
18578 case OO.ui.Keys.RIGHT:
18579 this.clearKeyPressBuffer();
18580 nextItem = this.getRelativeSelectableItem( currentItem, 1 );
18583 case OO.ui.Keys.ESCAPE:
18584 case OO.ui.Keys.TAB:
18585 if ( currentItem && currentItem.constructor.static.highlightable ) {
18586 currentItem.setHighlighted( false );
18588 this.unbindKeyDownListener();
18589 this.unbindKeyPressListener();
18590 // Don't prevent tabbing away / defocusing
18596 if ( nextItem.constructor.static.highlightable ) {
18597 this.highlightItem( nextItem );
18599 this.chooseItem( nextItem );
18601 nextItem.scrollElementIntoView();
18605 // Can't just return false, because e is not always a jQuery event
18606 e.preventDefault();
18607 e.stopPropagation();
18613 * Bind key down listener.
18617 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
18618 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler );
18622 * Unbind key down listener.
18626 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
18627 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler );
18631 * Clear the key-press buffer
18635 OO.ui.SelectWidget.prototype.clearKeyPressBuffer = function () {
18636 if ( this.keyPressBufferTimer ) {
18637 clearTimeout( this.keyPressBufferTimer );
18638 this.keyPressBufferTimer = null;
18640 this.keyPressBuffer = '';
18644 * Handle key press events.
18647 * @param {jQuery.Event} e Key press event
18649 OO.ui.SelectWidget.prototype.onKeyPress = function ( e ) {
18650 var c, filter, item;
18652 if ( !e.charCode ) {
18653 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.keyPressBuffer !== '' ) {
18654 this.keyPressBuffer = this.keyPressBuffer.substr( 0, this.keyPressBuffer.length - 1 );
18659 if ( String.fromCodePoint ) {
18660 c = String.fromCodePoint( e.charCode );
18662 c = String.fromCharCode( e.charCode );
18665 if ( this.keyPressBufferTimer ) {
18666 clearTimeout( this.keyPressBufferTimer );
18668 this.keyPressBufferTimer = setTimeout( this.clearKeyPressBuffer.bind( this ), 1500 );
18670 item = this.getHighlightedItem() || this.getSelectedItem();
18672 if ( this.keyPressBuffer === c ) {
18673 // Common (if weird) special case: typing "xxxx" will cycle through all
18674 // the items beginning with "x".
18676 item = this.getRelativeSelectableItem( item, 1 );
18679 this.keyPressBuffer += c;
18682 filter = this.getItemMatcher( this.keyPressBuffer, false );
18683 if ( !item || !filter( item ) ) {
18684 item = this.getRelativeSelectableItem( item, 1, filter );
18687 if ( item.constructor.static.highlightable ) {
18688 this.highlightItem( item );
18690 this.chooseItem( item );
18692 item.scrollElementIntoView();
18699 * Get a matcher for the specific string
18702 * @param {string} s String to match against items
18703 * @param {boolean} [exact=false] Only accept exact matches
18704 * @return {Function} function ( OO.ui.OptionItem ) => boolean
18706 OO.ui.SelectWidget.prototype.getItemMatcher = function ( s, exact ) {
18709 if ( s.normalize ) {
18712 s = exact ? s.trim() : s.replace( /^\s+/, '' );
18713 re = '^\\s*' + s.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
18717 re = new RegExp( re, 'i' );
18718 return function ( item ) {
18719 var l = item.getLabel();
18720 if ( typeof l !== 'string' ) {
18721 l = item.$label.text();
18723 if ( l.normalize ) {
18726 return re.test( l );
18731 * Bind key press listener.
18735 OO.ui.SelectWidget.prototype.bindKeyPressListener = function () {
18736 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler );
18740 * Unbind key down listener.
18742 * If you override this, be sure to call this.clearKeyPressBuffer() from your
18747 OO.ui.SelectWidget.prototype.unbindKeyPressListener = function () {
18748 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler );
18749 this.clearKeyPressBuffer();
18753 * Visibility change handler
18756 * @param {boolean} visible
18758 OO.ui.SelectWidget.prototype.onToggle = function ( visible ) {
18760 this.clearKeyPressBuffer();
18765 * Get the closest item to a jQuery.Event.
18768 * @param {jQuery.Event} e
18769 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
18771 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
18772 return $( e.target ).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
18776 * Get selected item.
18778 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
18780 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
18783 for ( i = 0, len = this.items.length; i < len; i++ ) {
18784 if ( this.items[ i ].isSelected() ) {
18785 return this.items[ i ];
18792 * Get highlighted item.
18794 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
18796 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
18799 for ( i = 0, len = this.items.length; i < len; i++ ) {
18800 if ( this.items[ i ].isHighlighted() ) {
18801 return this.items[ i ];
18808 * Toggle pressed state.
18810 * Press is a state that occurs when a user mouses down on an item, but
18811 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
18812 * until the user releases the mouse.
18814 * @param {boolean} pressed An option is being pressed
18816 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
18817 if ( pressed === undefined ) {
18818 pressed = !this.pressed;
18820 if ( pressed !== this.pressed ) {
18822 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
18823 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
18824 this.pressed = pressed;
18829 * Highlight an option. If the `item` param is omitted, no options will be highlighted
18830 * and any existing highlight will be removed. The highlight is mutually exclusive.
18832 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
18836 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
18837 var i, len, highlighted,
18840 for ( i = 0, len = this.items.length; i < len; i++ ) {
18841 highlighted = this.items[ i ] === item;
18842 if ( this.items[ i ].isHighlighted() !== highlighted ) {
18843 this.items[ i ].setHighlighted( highlighted );
18848 this.emit( 'highlight', item );
18855 * Fetch an item by its label.
18857 * @param {string} label Label of the item to select.
18858 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18859 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
18861 OO.ui.SelectWidget.prototype.getItemFromLabel = function ( label, prefix ) {
18862 var i, item, found,
18863 len = this.items.length,
18864 filter = this.getItemMatcher( label, true );
18866 for ( i = 0; i < len; i++ ) {
18867 item = this.items[ i ];
18868 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18875 filter = this.getItemMatcher( label, false );
18876 for ( i = 0; i < len; i++ ) {
18877 item = this.items[ i ];
18878 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18894 * Programmatically select an option by its label. If the item does not exist,
18895 * all options will be deselected.
18897 * @param {string} [label] Label of the item to select.
18898 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18902 OO.ui.SelectWidget.prototype.selectItemByLabel = function ( label, prefix ) {
18903 var itemFromLabel = this.getItemFromLabel( label, !!prefix );
18904 if ( label === undefined || !itemFromLabel ) {
18905 return this.selectItem();
18907 return this.selectItem( itemFromLabel );
18911 * Programmatically select an option by its data. If the `data` parameter is omitted,
18912 * or if the item does not exist, all options will be deselected.
18914 * @param {Object|string} [data] Value of the item to select, omit to deselect all
18918 OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) {
18919 var itemFromData = this.getItemFromData( data );
18920 if ( data === undefined || !itemFromData ) {
18921 return this.selectItem();
18923 return this.selectItem( itemFromData );
18927 * Programmatically select an option by its reference. If the `item` parameter is omitted,
18928 * all options will be deselected.
18930 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
18934 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
18935 var i, len, selected,
18938 for ( i = 0, len = this.items.length; i < len; i++ ) {
18939 selected = this.items[ i ] === item;
18940 if ( this.items[ i ].isSelected() !== selected ) {
18941 this.items[ i ].setSelected( selected );
18946 this.emit( 'select', item );
18955 * Press is a state that occurs when a user mouses down on an item, but has not
18956 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
18957 * releases the mouse.
18959 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
18963 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
18964 var i, len, pressed,
18967 for ( i = 0, len = this.items.length; i < len; i++ ) {
18968 pressed = this.items[ i ] === item;
18969 if ( this.items[ i ].isPressed() !== pressed ) {
18970 this.items[ i ].setPressed( pressed );
18975 this.emit( 'press', item );
18984 * Note that ‘choose’ should never be modified programmatically. A user can choose
18985 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
18986 * use the #selectItem method.
18988 * This method is identical to #selectItem, but may vary in subclasses that take additional action
18989 * when users choose an item with the keyboard or mouse.
18991 * @param {OO.ui.OptionWidget} item Item to choose
18995 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
18997 this.selectItem( item );
18998 this.emit( 'choose', item );
19005 * Get an option by its position relative to the specified item (or to the start of the option array,
19006 * if item is `null`). The direction in which to search through the option array is specified with a
19007 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
19008 * `null` if there are no options in the array.
19010 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
19011 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
19012 * @param {Function} filter Only consider items for which this function returns
19013 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
19014 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
19016 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction, filter ) {
19017 var currentIndex, nextIndex, i,
19018 increase = direction > 0 ? 1 : -1,
19019 len = this.items.length;
19021 if ( !$.isFunction( filter ) ) {
19022 filter = OO.ui.SelectWidget.static.passAllFilter;
19025 if ( item instanceof OO.ui.OptionWidget ) {
19026 currentIndex = this.items.indexOf( item );
19027 nextIndex = ( currentIndex + increase + len ) % len;
19029 // If no item is selected and moving forward, start at the beginning.
19030 // If moving backward, start at the end.
19031 nextIndex = direction > 0 ? 0 : len - 1;
19034 for ( i = 0; i < len; i++ ) {
19035 item = this.items[ nextIndex ];
19036 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
19039 nextIndex = ( nextIndex + increase + len ) % len;
19045 * Get the next selectable item or `null` if there are no selectable items.
19046 * Disabled options and menu-section markers and breaks are not selectable.
19048 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
19050 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
19053 for ( i = 0, len = this.items.length; i < len; i++ ) {
19054 item = this.items[ i ];
19055 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
19064 * Add an array of options to the select. Optionally, an index number can be used to
19065 * specify an insertion point.
19067 * @param {OO.ui.OptionWidget[]} items Items to add
19068 * @param {number} [index] Index to insert items after
19072 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
19074 OO.ui.mixin.GroupWidget.prototype.addItems.call( this, items, index );
19076 // Always provide an index, even if it was omitted
19077 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
19083 * Remove the specified array of options from the select. Options will be detached
19084 * from the DOM, not removed, so they can be reused later. To remove all options from
19085 * the select, you may wish to use the #clearItems method instead.
19087 * @param {OO.ui.OptionWidget[]} items Items to remove
19091 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
19094 // Deselect items being removed
19095 for ( i = 0, len = items.length; i < len; i++ ) {
19097 if ( item.isSelected() ) {
19098 this.selectItem( null );
19103 OO.ui.mixin.GroupWidget.prototype.removeItems.call( this, items );
19105 this.emit( 'remove', items );
19111 * Clear all options from the select. Options will be detached from the DOM, not removed,
19112 * so that they can be reused later. To remove a subset of options from the select, use
19113 * the #removeItems method.
19118 OO.ui.SelectWidget.prototype.clearItems = function () {
19119 var items = this.items.slice();
19122 OO.ui.mixin.GroupWidget.prototype.clearItems.call( this );
19125 this.selectItem( null );
19127 this.emit( 'remove', items );
19133 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
19134 * button options and is used together with
19135 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
19136 * highlighting, choosing, and selecting mutually exclusive options. Please see
19137 * the [OOjs UI documentation on MediaWiki] [1] for more information.
19140 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
19141 * var option1 = new OO.ui.ButtonOptionWidget( {
19143 * label: 'Option 1',
19144 * title: 'Button option 1'
19147 * var option2 = new OO.ui.ButtonOptionWidget( {
19149 * label: 'Option 2',
19150 * title: 'Button option 2'
19153 * var option3 = new OO.ui.ButtonOptionWidget( {
19155 * label: 'Option 3',
19156 * title: 'Button option 3'
19159 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
19160 * items: [ option1, option2, option3 ]
19162 * $( 'body' ).append( buttonSelect.$element );
19164 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
19167 * @extends OO.ui.SelectWidget
19168 * @mixins OO.ui.mixin.TabIndexedElement
19171 * @param {Object} [config] Configuration options
19173 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
19174 // Parent constructor
19175 OO.ui.ButtonSelectWidget.parent.call( this, config );
19177 // Mixin constructors
19178 OO.ui.mixin.TabIndexedElement.call( this, config );
19181 this.$element.on( {
19182 focus: this.bindKeyDownListener.bind( this ),
19183 blur: this.unbindKeyDownListener.bind( this )
19187 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
19192 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
19193 OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.mixin.TabIndexedElement );
19196 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
19197 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
19198 * an interface for adding, removing and selecting options.
19199 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
19201 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
19202 * OO.ui.RadioSelectInputWidget instead.
19205 * // A RadioSelectWidget with RadioOptions.
19206 * var option1 = new OO.ui.RadioOptionWidget( {
19208 * label: 'Selected radio option'
19211 * var option2 = new OO.ui.RadioOptionWidget( {
19213 * label: 'Unselected radio option'
19216 * var radioSelect=new OO.ui.RadioSelectWidget( {
19217 * items: [ option1, option2 ]
19220 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
19221 * radioSelect.selectItem( option1 );
19223 * $( 'body' ).append( radioSelect.$element );
19225 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
19229 * @extends OO.ui.SelectWidget
19230 * @mixins OO.ui.mixin.TabIndexedElement
19233 * @param {Object} [config] Configuration options
19235 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
19236 // Parent constructor
19237 OO.ui.RadioSelectWidget.parent.call( this, config );
19239 // Mixin constructors
19240 OO.ui.mixin.TabIndexedElement.call( this, config );
19243 this.$element.on( {
19244 focus: this.bindKeyDownListener.bind( this ),
19245 blur: this.unbindKeyDownListener.bind( this )
19250 .addClass( 'oo-ui-radioSelectWidget' )
19251 .attr( 'role', 'radiogroup' );
19256 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
19257 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement );
19260 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
19261 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
19262 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
19263 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
19264 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
19265 * and customized to be opened, closed, and displayed as needed.
19267 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
19268 * mouse outside the menu.
19270 * Menus also have support for keyboard interaction:
19272 * - Enter/Return key: choose and select a menu option
19273 * - Up-arrow key: highlight the previous menu option
19274 * - Down-arrow key: highlight the next menu option
19275 * - Esc key: hide the menu
19277 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
19278 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
19281 * @extends OO.ui.SelectWidget
19282 * @mixins OO.ui.mixin.ClippableElement
19285 * @param {Object} [config] Configuration options
19286 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
19287 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
19288 * and {@link OO.ui.mixin.LookupElement LookupElement}
19289 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
19290 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiSelectWidget CapsuleMultiSelectWidget}
19291 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
19292 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
19293 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
19294 * that button, unless the button (or its parent widget) is passed in here.
19295 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
19296 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
19298 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
19299 // Configuration initialization
19300 config = config || {};
19302 // Parent constructor
19303 OO.ui.MenuSelectWidget.parent.call( this, config );
19305 // Mixin constructors
19306 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
19309 this.newItems = null;
19310 this.autoHide = config.autoHide === undefined || !!config.autoHide;
19311 this.filterFromInput = !!config.filterFromInput;
19312 this.$input = config.$input ? config.$input : config.input ? config.input.$input : null;
19313 this.$widget = config.widget ? config.widget.$element : null;
19314 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
19315 this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 );
19319 .addClass( 'oo-ui-menuSelectWidget' )
19320 .attr( 'role', 'menu' );
19322 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
19323 // that reference properties not initialized at that time of parent class construction
19324 // TODO: Find a better way to handle post-constructor setup
19325 this.visible = false;
19326 this.$element.addClass( 'oo-ui-element-hidden' );
19331 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
19332 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement );
19337 * Handles document mouse down events.
19340 * @param {jQuery.Event} e Key down event
19342 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
19344 !OO.ui.contains( this.$element[ 0 ], e.target, true ) &&
19345 ( !this.$widget || !OO.ui.contains( this.$widget[ 0 ], e.target, true ) )
19347 this.toggle( false );
19354 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
19355 var currentItem = this.getHighlightedItem() || this.getSelectedItem();
19357 if ( !this.isDisabled() && this.isVisible() ) {
19358 switch ( e.keyCode ) {
19359 case OO.ui.Keys.LEFT:
19360 case OO.ui.Keys.RIGHT:
19361 // Do nothing if a text field is associated, arrow keys will be handled natively
19362 if ( !this.$input ) {
19363 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
19366 case OO.ui.Keys.ESCAPE:
19367 case OO.ui.Keys.TAB:
19368 if ( currentItem ) {
19369 currentItem.setHighlighted( false );
19371 this.toggle( false );
19372 // Don't prevent tabbing away, prevent defocusing
19373 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
19374 e.preventDefault();
19375 e.stopPropagation();
19379 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
19386 * Update menu item visibility after input changes.
19389 OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () {
19391 len = this.items.length,
19392 showAll = !this.isVisible(),
19393 filter = showAll ? null : this.getItemMatcher( this.$input.val() );
19395 for ( i = 0; i < len; i++ ) {
19396 item = this.items[ i ];
19397 if ( item instanceof OO.ui.OptionWidget ) {
19398 item.toggle( showAll || filter( item ) );
19402 // Reevaluate clipping
19409 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
19410 if ( this.$input ) {
19411 this.$input.on( 'keydown', this.onKeyDownHandler );
19413 OO.ui.MenuSelectWidget.parent.prototype.bindKeyDownListener.call( this );
19420 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
19421 if ( this.$input ) {
19422 this.$input.off( 'keydown', this.onKeyDownHandler );
19424 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyDownListener.call( this );
19431 OO.ui.MenuSelectWidget.prototype.bindKeyPressListener = function () {
19432 if ( this.$input ) {
19433 if ( this.filterFromInput ) {
19434 this.$input.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
19437 OO.ui.MenuSelectWidget.parent.prototype.bindKeyPressListener.call( this );
19444 OO.ui.MenuSelectWidget.prototype.unbindKeyPressListener = function () {
19445 if ( this.$input ) {
19446 if ( this.filterFromInput ) {
19447 this.$input.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
19448 this.updateItemVisibility();
19451 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyPressListener.call( this );
19458 * When a user chooses an item, the menu is closed.
19460 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
19461 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
19462 * @param {OO.ui.OptionWidget} item Item to choose
19465 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
19466 OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item );
19467 this.toggle( false );
19474 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
19478 OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index );
19481 if ( !this.newItems ) {
19482 this.newItems = [];
19485 for ( i = 0, len = items.length; i < len; i++ ) {
19487 if ( this.isVisible() ) {
19488 // Defer fitting label until item has been attached
19491 this.newItems.push( item );
19495 // Reevaluate clipping
19504 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
19506 OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items );
19508 // Reevaluate clipping
19517 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
19519 OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this );
19521 // Reevaluate clipping
19530 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
19531 var i, len, change;
19533 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
19534 change = visible !== this.isVisible();
19537 OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible );
19541 this.bindKeyDownListener();
19542 this.bindKeyPressListener();
19544 if ( this.newItems && this.newItems.length ) {
19545 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
19546 this.newItems[ i ].fitLabel();
19548 this.newItems = null;
19550 this.toggleClipping( true );
19553 if ( this.autoHide ) {
19554 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler );
19557 this.unbindKeyDownListener();
19558 this.unbindKeyPressListener();
19559 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler );
19560 this.toggleClipping( false );
19568 * FloatingMenuSelectWidget is a menu that will stick under a specified
19569 * container, even when it is inserted elsewhere in the document (for example,
19570 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
19571 * menu from being clipped too aggresively.
19573 * The menu's position is automatically calculated and maintained when the menu
19574 * is toggled or the window is resized.
19576 * See OO.ui.ComboBoxInputWidget for an example of a widget that uses this class.
19579 * @extends OO.ui.MenuSelectWidget
19580 * @mixins OO.ui.mixin.FloatableElement
19583 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
19584 * Deprecated, omit this parameter and specify `$container` instead.
19585 * @param {Object} [config] Configuration options
19586 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
19588 OO.ui.FloatingMenuSelectWidget = function OoUiFloatingMenuSelectWidget( inputWidget, config ) {
19589 // Allow 'inputWidget' parameter and config for backwards compatibility
19590 if ( OO.isPlainObject( inputWidget ) && config === undefined ) {
19591 config = inputWidget;
19592 inputWidget = config.inputWidget;
19595 // Configuration initialization
19596 config = config || {};
19598 // Parent constructor
19599 OO.ui.FloatingMenuSelectWidget.parent.call( this, config );
19601 // Properties (must be set before mixin constructors)
19602 this.inputWidget = inputWidget; // For backwards compatibility
19603 this.$container = config.$container || this.inputWidget.$element;
19605 // Mixins constructors
19606 OO.ui.mixin.FloatableElement.call( this, $.extend( {}, config, { $floatableContainer: this.$container } ) );
19609 this.$element.addClass( 'oo-ui-floatingMenuSelectWidget' );
19610 // For backwards compatibility
19611 this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' );
19616 OO.inheritClass( OO.ui.FloatingMenuSelectWidget, OO.ui.MenuSelectWidget );
19617 OO.mixinClass( OO.ui.FloatingMenuSelectWidget, OO.ui.mixin.FloatableElement );
19619 // For backwards compatibility
19620 OO.ui.TextInputMenuSelectWidget = OO.ui.FloatingMenuSelectWidget;
19627 OO.ui.FloatingMenuSelectWidget.prototype.toggle = function ( visible ) {
19629 visible = visible === undefined ? !this.isVisible() : !!visible;
19630 change = visible !== this.isVisible();
19632 if ( change && visible ) {
19633 // Make sure the width is set before the parent method runs.
19634 this.setIdealSize( this.$container.width() );
19638 // This will call this.clip(), which is nonsensical since we're not positioned yet...
19639 OO.ui.FloatingMenuSelectWidget.parent.prototype.toggle.call( this, visible );
19642 this.togglePositioning( this.isVisible() );
19649 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
19650 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
19652 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
19655 * @extends OO.ui.SelectWidget
19656 * @mixins OO.ui.mixin.TabIndexedElement
19659 * @param {Object} [config] Configuration options
19661 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
19662 // Parent constructor
19663 OO.ui.OutlineSelectWidget.parent.call( this, config );
19665 // Mixin constructors
19666 OO.ui.mixin.TabIndexedElement.call( this, config );
19669 this.$element.on( {
19670 focus: this.bindKeyDownListener.bind( this ),
19671 blur: this.unbindKeyDownListener.bind( this )
19675 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
19680 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
19681 OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.mixin.TabIndexedElement );
19684 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
19686 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
19689 * @extends OO.ui.SelectWidget
19690 * @mixins OO.ui.mixin.TabIndexedElement
19693 * @param {Object} [config] Configuration options
19695 OO.ui.TabSelectWidget = function OoUiTabSelectWidget( config ) {
19696 // Parent constructor
19697 OO.ui.TabSelectWidget.parent.call( this, config );
19699 // Mixin constructors
19700 OO.ui.mixin.TabIndexedElement.call( this, config );
19703 this.$element.on( {
19704 focus: this.bindKeyDownListener.bind( this ),
19705 blur: this.unbindKeyDownListener.bind( this )
19709 this.$element.addClass( 'oo-ui-tabSelectWidget' );
19714 OO.inheritClass( OO.ui.TabSelectWidget, OO.ui.SelectWidget );
19715 OO.mixinClass( OO.ui.TabSelectWidget, OO.ui.mixin.TabIndexedElement );
19718 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
19719 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
19720 * (to adjust the value in increments) to allow the user to enter a number.
19723 * // Example: A NumberInputWidget.
19724 * var numberInput = new OO.ui.NumberInputWidget( {
19725 * label: 'NumberInputWidget',
19726 * input: { value: 5, min: 1, max: 10 }
19728 * $( 'body' ).append( numberInput.$element );
19731 * @extends OO.ui.Widget
19734 * @param {Object} [config] Configuration options
19735 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
19736 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
19737 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
19738 * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
19739 * @cfg {number} [min=-Infinity] Minimum allowed value
19740 * @cfg {number} [max=Infinity] Maximum allowed value
19741 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
19742 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
19744 OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
19745 // Configuration initialization
19746 config = $.extend( {
19754 // Parent constructor
19755 OO.ui.NumberInputWidget.parent.call( this, config );
19758 this.input = new OO.ui.TextInputWidget( $.extend(
19760 disabled: this.isDisabled()
19764 this.minusButton = new OO.ui.ButtonWidget( $.extend(
19766 disabled: this.isDisabled(),
19769 config.minusButton,
19771 classes: [ 'oo-ui-numberInputWidget-minusButton' ],
19775 this.plusButton = new OO.ui.ButtonWidget( $.extend(
19777 disabled: this.isDisabled(),
19782 classes: [ 'oo-ui-numberInputWidget-plusButton' ],
19788 this.input.connect( this, {
19789 change: this.emit.bind( this, 'change' ),
19790 enter: this.emit.bind( this, 'enter' )
19792 this.input.$input.on( {
19793 keydown: this.onKeyDown.bind( this ),
19794 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
19796 this.plusButton.connect( this, {
19797 click: [ 'onButtonClick', +1 ]
19799 this.minusButton.connect( this, {
19800 click: [ 'onButtonClick', -1 ]
19804 this.setIsInteger( !!config.isInteger );
19805 this.setRange( config.min, config.max );
19806 this.setStep( config.step, config.pageStep );
19808 this.$field = $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
19810 this.minusButton.$element,
19811 this.input.$element,
19812 this.plusButton.$element
19814 this.$element.addClass( 'oo-ui-numberInputWidget' ).append( this.$field );
19815 this.input.setValidation( this.validateNumber.bind( this ) );
19820 OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.Widget );
19825 * A `change` event is emitted when the value of the input changes.
19831 * An `enter` event is emitted when the user presses 'enter' inside the text box.
19839 * Set whether only integers are allowed
19840 * @param {boolean} flag
19842 OO.ui.NumberInputWidget.prototype.setIsInteger = function ( flag ) {
19843 this.isInteger = !!flag;
19844 this.input.setValidityFlag();
19848 * Get whether only integers are allowed
19849 * @return {boolean} Flag value
19851 OO.ui.NumberInputWidget.prototype.getIsInteger = function () {
19852 return this.isInteger;
19856 * Set the range of allowed values
19857 * @param {number} min Minimum allowed value
19858 * @param {number} max Maximum allowed value
19860 OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
19862 throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
19866 this.input.setValidityFlag();
19870 * Get the current range
19871 * @return {number[]} Minimum and maximum values
19873 OO.ui.NumberInputWidget.prototype.getRange = function () {
19874 return [ this.min, this.max ];
19878 * Set the stepping deltas
19879 * @param {number} step Normal step
19880 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
19882 OO.ui.NumberInputWidget.prototype.setStep = function ( step, pageStep ) {
19884 throw new Error( 'Step value must be positive' );
19886 if ( pageStep === null ) {
19887 pageStep = step * 10;
19888 } else if ( pageStep <= 0 ) {
19889 throw new Error( 'Page step value must be positive' );
19892 this.pageStep = pageStep;
19896 * Get the current stepping values
19897 * @return {number[]} Step and page step
19899 OO.ui.NumberInputWidget.prototype.getStep = function () {
19900 return [ this.step, this.pageStep ];
19904 * Get the current value of the widget
19907 OO.ui.NumberInputWidget.prototype.getValue = function () {
19908 return this.input.getValue();
19912 * Get the current value of the widget as a number
19913 * @return {number} May be NaN, or an invalid number
19915 OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
19916 return +this.input.getValue();
19920 * Set the value of the widget
19921 * @param {string} value Invalid values are allowed
19923 OO.ui.NumberInputWidget.prototype.setValue = function ( value ) {
19924 this.input.setValue( value );
19928 * Adjust the value of the widget
19929 * @param {number} delta Adjustment amount
19931 OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
19932 var n, v = this.getNumericValue();
19935 if ( isNaN( delta ) || !isFinite( delta ) ) {
19936 throw new Error( 'Delta must be a finite number' );
19939 if ( isNaN( v ) ) {
19943 n = Math.max( Math.min( n, this.max ), this.min );
19944 if ( this.isInteger ) {
19945 n = Math.round( n );
19950 this.setValue( n );
19957 * @param {string} value Field value
19958 * @return {boolean}
19960 OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
19962 if ( isNaN( n ) || !isFinite( n ) ) {
19966 /*jshint bitwise: false */
19967 if ( this.isInteger && ( n | 0 ) !== n ) {
19970 /*jshint bitwise: true */
19972 if ( n < this.min || n > this.max ) {
19980 * Handle mouse click events.
19983 * @param {number} dir +1 or -1
19985 OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
19986 this.adjustValue( dir * this.step );
19990 * Handle mouse wheel events.
19993 * @param {jQuery.Event} event
19995 OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
19998 // Standard 'wheel' event
19999 if ( event.originalEvent.deltaMode !== undefined ) {
20000 this.sawWheelEvent = true;
20002 if ( event.originalEvent.deltaY ) {
20003 delta = -event.originalEvent.deltaY;
20004 } else if ( event.originalEvent.deltaX ) {
20005 delta = event.originalEvent.deltaX;
20008 // Non-standard events
20009 if ( !this.sawWheelEvent ) {
20010 if ( event.originalEvent.wheelDeltaX ) {
20011 delta = -event.originalEvent.wheelDeltaX;
20012 } else if ( event.originalEvent.wheelDeltaY ) {
20013 delta = event.originalEvent.wheelDeltaY;
20014 } else if ( event.originalEvent.wheelDelta ) {
20015 delta = event.originalEvent.wheelDelta;
20016 } else if ( event.originalEvent.detail ) {
20017 delta = -event.originalEvent.detail;
20022 delta = delta < 0 ? -1 : 1;
20023 this.adjustValue( delta * this.step );
20030 * Handle key down events.
20033 * @param {jQuery.Event} e Key down event
20035 OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
20036 if ( !this.isDisabled() ) {
20037 switch ( e.which ) {
20038 case OO.ui.Keys.UP:
20039 this.adjustValue( this.step );
20041 case OO.ui.Keys.DOWN:
20042 this.adjustValue( -this.step );
20044 case OO.ui.Keys.PAGEUP:
20045 this.adjustValue( this.pageStep );
20047 case OO.ui.Keys.PAGEDOWN:
20048 this.adjustValue( -this.pageStep );
20057 OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
20059 OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
20061 if ( this.input ) {
20062 this.input.setDisabled( this.isDisabled() );
20064 if ( this.minusButton ) {
20065 this.minusButton.setDisabled( this.isDisabled() );
20067 if ( this.plusButton ) {
20068 this.plusButton.setDisabled( this.isDisabled() );
20075 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
20076 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
20077 * visually by a slider in the leftmost position.
20080 * // Toggle switches in the 'off' and 'on' position.
20081 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
20082 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
20086 * // Create a FieldsetLayout to layout and label switches
20087 * var fieldset = new OO.ui.FieldsetLayout( {
20088 * label: 'Toggle switches'
20090 * fieldset.addItems( [
20091 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
20092 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
20094 * $( 'body' ).append( fieldset.$element );
20097 * @extends OO.ui.ToggleWidget
20098 * @mixins OO.ui.mixin.TabIndexedElement
20101 * @param {Object} [config] Configuration options
20102 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
20103 * By default, the toggle switch is in the 'off' position.
20105 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
20106 // Parent constructor
20107 OO.ui.ToggleSwitchWidget.parent.call( this, config );
20109 // Mixin constructors
20110 OO.ui.mixin.TabIndexedElement.call( this, config );
20113 this.dragging = false;
20114 this.dragStart = null;
20115 this.sliding = false;
20116 this.$glow = $( '<span>' );
20117 this.$grip = $( '<span>' );
20120 this.$element.on( {
20121 click: this.onClick.bind( this ),
20122 keypress: this.onKeyPress.bind( this )
20126 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
20127 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
20129 .addClass( 'oo-ui-toggleSwitchWidget' )
20130 .attr( 'role', 'checkbox' )
20131 .append( this.$glow, this.$grip );
20136 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
20137 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.mixin.TabIndexedElement );
20142 * Handle mouse click events.
20145 * @param {jQuery.Event} e Mouse click event
20147 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
20148 if ( !this.isDisabled() && e.which === 1 ) {
20149 this.setValue( !this.value );
20155 * Handle key press events.
20158 * @param {jQuery.Event} e Key press event
20160 OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) {
20161 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
20162 this.setValue( !this.value );