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-11-03T21:42:20Z
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.
354 * @param {string} key Message key
355 * @param {Mixed...} [params] Message parameters
356 * @return {string} Translated message with parameters substituted
358 OO
.ui
.msg = function ( key
) {
359 var message
= messages
[ key
],
360 params
= Array
.prototype.slice
.call( arguments
, 1 );
361 if ( typeof message
=== 'string' ) {
362 // Perform $1 substitution
363 message
= message
.replace( /\$(\d+)/g, function ( unused
, n
) {
364 var i
= parseInt( n
, 10 );
365 return params
[ i
- 1 ] !== undefined ? params
[ i
- 1 ] : '$' + n
;
368 // Return placeholder if message not found
369 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;
440 * Namespace for OOjs UI mixins.
442 * Mixins are named according to the type of object they are intended to
443 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
444 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
445 * is intended to be mixed in to an instance of OO.ui.Widget.
453 * PendingElement is a mixin that is used to create elements that notify users that something is happening
454 * and that they should wait before proceeding. The pending state is visually represented with a pending
455 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
456 * field of a {@link OO.ui.TextInputWidget text input widget}.
458 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
459 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
460 * in process dialogs.
463 * function MessageDialog( config ) {
464 * MessageDialog.parent.call( this, config );
466 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
468 * MessageDialog.static.actions = [
469 * { action: 'save', label: 'Done', flags: 'primary' },
470 * { label: 'Cancel', flags: 'safe' }
473 * MessageDialog.prototype.initialize = function () {
474 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
475 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
476 * 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>' );
477 * this.$body.append( this.content.$element );
479 * MessageDialog.prototype.getBodyHeight = function () {
482 * MessageDialog.prototype.getActionProcess = function ( action ) {
484 * if ( action === 'save' ) {
485 * dialog.getActions().get({actions: 'save'})[0].pushPending();
486 * return new OO.ui.Process()
488 * .next( function () {
489 * dialog.getActions().get({actions: 'save'})[0].popPending();
492 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
495 * var windowManager = new OO.ui.WindowManager();
496 * $( 'body' ).append( windowManager.$element );
498 * var dialog = new MessageDialog();
499 * windowManager.addWindows( [ dialog ] );
500 * windowManager.openWindow( dialog );
506 * @param {Object} [config] Configuration options
507 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
509 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
510 // Configuration initialization
511 config
= config
|| {};
515 this.$pending
= null;
518 this.setPendingElement( config
.$pending
|| this.$element
);
523 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
528 * Set the pending element (and clean up any existing one).
530 * @param {jQuery} $pending The element to set to pending.
532 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
533 if ( this.$pending
) {
534 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
537 this.$pending
= $pending
;
538 if ( this.pending
> 0 ) {
539 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
544 * Check if an element is pending.
546 * @return {boolean} Element is pending
548 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
549 return !!this.pending
;
553 * Increase the pending counter. The pending state will remain active until the counter is zero
554 * (i.e., the number of calls to #pushPending and #popPending is the same).
558 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
559 if ( this.pending
=== 0 ) {
560 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
561 this.updateThemeClasses();
569 * Decrease the pending counter. The pending state will remain active until the counter is zero
570 * (i.e., the number of calls to #pushPending and #popPending is the same).
574 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
575 if ( this.pending
=== 1 ) {
576 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
577 this.updateThemeClasses();
579 this.pending
= Math
.max( 0, this.pending
- 1 );
585 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
586 * Actions can be made available for specific contexts (modes) and circumstances
587 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
589 * ActionSets contain two types of actions:
591 * - 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.
592 * - Other: Other actions include all non-special visible actions.
594 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
597 * // Example: An action set used in a process dialog
598 * function MyProcessDialog( config ) {
599 * MyProcessDialog.parent.call( this, config );
601 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
602 * MyProcessDialog.static.title = 'An action set in a process dialog';
603 * // An action set that uses modes ('edit' and 'help' mode, in this example).
604 * MyProcessDialog.static.actions = [
605 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
606 * { action: 'help', modes: 'edit', label: 'Help' },
607 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
608 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
611 * MyProcessDialog.prototype.initialize = function () {
612 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
613 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
614 * 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>' );
615 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
616 * 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>' );
617 * this.stackLayout = new OO.ui.StackLayout( {
618 * items: [ this.panel1, this.panel2 ]
620 * this.$body.append( this.stackLayout.$element );
622 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
623 * return MyProcessDialog.parent.prototype.getSetupProcess.call( this, data )
624 * .next( function () {
625 * this.actions.setMode( 'edit' );
628 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
629 * if ( action === 'help' ) {
630 * this.actions.setMode( 'help' );
631 * this.stackLayout.setItem( this.panel2 );
632 * } else if ( action === 'back' ) {
633 * this.actions.setMode( 'edit' );
634 * this.stackLayout.setItem( this.panel1 );
635 * } else if ( action === 'continue' ) {
637 * return new OO.ui.Process( function () {
641 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
643 * MyProcessDialog.prototype.getBodyHeight = function () {
644 * return this.panel1.$element.outerHeight( true );
646 * var windowManager = new OO.ui.WindowManager();
647 * $( 'body' ).append( windowManager.$element );
648 * var dialog = new MyProcessDialog( {
651 * windowManager.addWindows( [ dialog ] );
652 * windowManager.openWindow( dialog );
654 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
658 * @mixins OO.EventEmitter
661 * @param {Object} [config] Configuration options
663 OO
.ui
.ActionSet
= function OoUiActionSet( config
) {
664 // Configuration initialization
665 config
= config
|| {};
667 // Mixin constructors
668 OO
.EventEmitter
.call( this );
673 actions
: 'getAction',
677 this.categorized
= {};
680 this.organized
= false;
681 this.changing
= false;
682 this.changed
= false;
687 OO
.mixinClass( OO
.ui
.ActionSet
, OO
.EventEmitter
);
689 /* Static Properties */
692 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
693 * header of a {@link OO.ui.ProcessDialog process dialog}.
694 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
696 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
703 OO
.ui
.ActionSet
.static.specialFlags
= [ 'safe', 'primary' ];
710 * A 'click' event is emitted when an action is clicked.
712 * @param {OO.ui.ActionWidget} action Action that was clicked
718 * A 'resize' event is emitted when an action widget is resized.
720 * @param {OO.ui.ActionWidget} action Action that was resized
726 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
728 * @param {OO.ui.ActionWidget[]} added Actions added
734 * A 'remove' event is emitted when actions are {@link #method-remove removed}
735 * or {@link #clear cleared}.
737 * @param {OO.ui.ActionWidget[]} added Actions removed
743 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
744 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
751 * Handle action change events.
756 OO
.ui
.ActionSet
.prototype.onActionChange = function () {
757 this.organized
= false;
758 if ( this.changing
) {
761 this.emit( 'change' );
766 * Check if an action is one of the special actions.
768 * @param {OO.ui.ActionWidget} action Action to check
769 * @return {boolean} Action is special
771 OO
.ui
.ActionSet
.prototype.isSpecial = function ( action
) {
774 for ( flag
in this.special
) {
775 if ( action
=== this.special
[ flag
] ) {
784 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
787 * @param {Object} [filters] Filters to use, omit to get all actions
788 * @param {string|string[]} [filters.actions] Actions that action widgets must have
789 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
790 * @param {string|string[]} [filters.modes] Modes that action widgets must have
791 * @param {boolean} [filters.visible] Action widgets must be visible
792 * @param {boolean} [filters.disabled] Action widgets must be disabled
793 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
795 OO
.ui
.ActionSet
.prototype.get = function ( filters
) {
796 var i
, len
, list
, category
, actions
, index
, match
, matches
;
801 // Collect category candidates
803 for ( category
in this.categorized
) {
804 list
= filters
[ category
];
806 if ( !Array
.isArray( list
) ) {
809 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
810 actions
= this.categorized
[ category
][ list
[ i
] ];
811 if ( Array
.isArray( actions
) ) {
812 matches
.push
.apply( matches
, actions
);
817 // Remove by boolean filters
818 for ( i
= 0, len
= matches
.length
; i
< len
; i
++ ) {
819 match
= matches
[ i
];
821 ( filters
.visible
!== undefined && match
.isVisible() !== filters
.visible
) ||
822 ( filters
.disabled
!== undefined && match
.isDisabled() !== filters
.disabled
)
824 matches
.splice( i
, 1 );
830 for ( i
= 0, len
= matches
.length
; i
< len
; i
++ ) {
831 match
= matches
[ i
];
832 index
= matches
.lastIndexOf( match
);
833 while ( index
!== i
) {
834 matches
.splice( index
, 1 );
836 index
= matches
.lastIndexOf( match
);
841 return this.list
.slice();
845 * Get 'special' actions.
847 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
848 * Special flags can be configured in subclasses by changing the static #specialFlags property.
850 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
852 OO
.ui
.ActionSet
.prototype.getSpecial = function () {
854 return $.extend( {}, this.special
);
858 * Get 'other' actions.
860 * Other actions include all non-special visible action widgets.
862 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
864 OO
.ui
.ActionSet
.prototype.getOthers = function () {
866 return this.others
.slice();
870 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
871 * to be available in the specified mode will be made visible. All other actions will be hidden.
873 * @param {string} mode The mode. Only actions configured to be available in the specified
874 * mode will be made visible.
879 OO
.ui
.ActionSet
.prototype.setMode = function ( mode
) {
882 this.changing
= true;
883 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
884 action
= this.list
[ i
];
885 action
.toggle( action
.hasMode( mode
) );
888 this.organized
= false;
889 this.changing
= false;
890 this.emit( 'change' );
896 * Set the abilities of the specified actions.
898 * Action widgets that are configured with the specified actions will be enabled
899 * or disabled based on the boolean values specified in the `actions`
902 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
903 * values that indicate whether or not the action should be enabled.
906 OO
.ui
.ActionSet
.prototype.setAbilities = function ( actions
) {
907 var i
, len
, action
, item
;
909 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
910 item
= this.list
[ i
];
911 action
= item
.getAction();
912 if ( actions
[ action
] !== undefined ) {
913 item
.setDisabled( !actions
[ action
] );
921 * Executes a function once per action.
923 * When making changes to multiple actions, use this method instead of iterating over the actions
924 * manually to defer emitting a #change event until after all actions have been changed.
926 * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get
927 * @param {Function} callback Callback to run for each action; callback is invoked with three
928 * arguments: the action, the action's index, the list of actions being iterated over
931 OO
.ui
.ActionSet
.prototype.forEach = function ( filter
, callback
) {
932 this.changed
= false;
933 this.changing
= true;
934 this.get( filter
).forEach( callback
);
935 this.changing
= false;
936 if ( this.changed
) {
937 this.emit( 'change' );
944 * Add action widgets to the action set.
946 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
951 OO
.ui
.ActionSet
.prototype.add = function ( actions
) {
954 this.changing
= true;
955 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
956 action
= actions
[ i
];
957 action
.connect( this, {
958 click
: [ 'emit', 'click', action
],
959 resize
: [ 'emit', 'resize', action
],
960 toggle
: [ 'onActionChange' ]
962 this.list
.push( action
);
964 this.organized
= false;
965 this.emit( 'add', actions
);
966 this.changing
= false;
967 this.emit( 'change' );
973 * Remove action widgets from the set.
975 * To remove all actions, you may wish to use the #clear method instead.
977 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
982 OO
.ui
.ActionSet
.prototype.remove = function ( actions
) {
983 var i
, len
, index
, action
;
985 this.changing
= true;
986 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
987 action
= actions
[ i
];
988 index
= this.list
.indexOf( action
);
989 if ( index
!== -1 ) {
990 action
.disconnect( this );
991 this.list
.splice( index
, 1 );
994 this.organized
= false;
995 this.emit( 'remove', actions
);
996 this.changing
= false;
997 this.emit( 'change' );
1003 * Remove all action widets from the set.
1005 * To remove only specified actions, use the {@link #method-remove remove} method instead.
1011 OO
.ui
.ActionSet
.prototype.clear = function () {
1013 removed
= this.list
.slice();
1015 this.changing
= true;
1016 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
1017 action
= this.list
[ i
];
1018 action
.disconnect( this );
1023 this.organized
= false;
1024 this.emit( 'remove', removed
);
1025 this.changing
= false;
1026 this.emit( 'change' );
1034 * This is called whenever organized information is requested. It will only reorganize the actions
1035 * if something has changed since the last time it ran.
1040 OO
.ui
.ActionSet
.prototype.organize = function () {
1041 var i
, iLen
, j
, jLen
, flag
, action
, category
, list
, item
, special
,
1042 specialFlags
= this.constructor.static.specialFlags
;
1044 if ( !this.organized
) {
1045 this.categorized
= {};
1048 for ( i
= 0, iLen
= this.list
.length
; i
< iLen
; i
++ ) {
1049 action
= this.list
[ i
];
1050 if ( action
.isVisible() ) {
1051 // Populate categories
1052 for ( category
in this.categories
) {
1053 if ( !this.categorized
[ category
] ) {
1054 this.categorized
[ category
] = {};
1056 list
= action
[ this.categories
[ category
] ]();
1057 if ( !Array
.isArray( list
) ) {
1060 for ( j
= 0, jLen
= list
.length
; j
< jLen
; j
++ ) {
1062 if ( !this.categorized
[ category
][ item
] ) {
1063 this.categorized
[ category
][ item
] = [];
1065 this.categorized
[ category
][ item
].push( action
);
1068 // Populate special/others
1070 for ( j
= 0, jLen
= specialFlags
.length
; j
< jLen
; j
++ ) {
1071 flag
= specialFlags
[ j
];
1072 if ( !this.special
[ flag
] && action
.hasFlag( flag
) ) {
1073 this.special
[ flag
] = action
;
1079 this.others
.push( action
);
1083 this.organized
= true;
1090 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
1091 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
1092 * connected to them and can't be interacted with.
1098 * @param {Object} [config] Configuration options
1099 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
1100 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
1102 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
1103 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
1104 * @cfg {string} [text] Text to insert
1105 * @cfg {Array} [content] An array of content elements to append (after #text).
1106 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
1107 * Instances of OO.ui.Element will have their $element appended.
1108 * @cfg {jQuery} [$content] Content elements to append (after #text).
1109 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
1110 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
1111 * Data can also be specified with the #setData method.
1113 OO
.ui
.Element
= function OoUiElement( config
) {
1114 // Configuration initialization
1115 config
= config
|| {};
1119 this.visible
= true;
1120 this.data
= config
.data
;
1121 this.$element
= config
.$element
||
1122 $( document
.createElement( this.getTagName() ) );
1123 this.elementGroup
= null;
1124 this.debouncedUpdateThemeClassesHandler
= OO
.ui
.debounce( this.debouncedUpdateThemeClasses
);
1127 if ( Array
.isArray( config
.classes
) ) {
1128 this.$element
.addClass( config
.classes
.join( ' ' ) );
1131 this.$element
.attr( 'id', config
.id
);
1133 if ( config
.text
) {
1134 this.$element
.text( config
.text
);
1136 if ( config
.content
) {
1137 // The `content` property treats plain strings as text; use an
1138 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
1139 // appropriate $element appended.
1140 this.$element
.append( config
.content
.map( function ( v
) {
1141 if ( typeof v
=== 'string' ) {
1142 // Escape string so it is properly represented in HTML.
1143 return document
.createTextNode( v
);
1144 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
1146 return v
.toString();
1147 } else if ( v
instanceof OO
.ui
.Element
) {
1153 if ( config
.$content
) {
1154 // The `$content` property treats plain strings as HTML.
1155 this.$element
.append( config
.$content
);
1161 OO
.initClass( OO
.ui
.Element
);
1163 /* Static Properties */
1166 * The name of the HTML tag used by the element.
1168 * The static value may be ignored if the #getTagName method is overridden.
1172 * @property {string}
1174 OO
.ui
.Element
.static.tagName
= 'div';
1176 /* Static Methods */
1179 * Reconstitute a JavaScript object corresponding to a widget created
1180 * by the PHP implementation.
1182 * @param {string|HTMLElement|jQuery} idOrNode
1183 * A DOM id (if a string) or node for the widget to infuse.
1184 * @return {OO.ui.Element}
1185 * The `OO.ui.Element` corresponding to this (infusable) document node.
1186 * For `Tag` objects emitted on the HTML side (used occasionally for content)
1187 * the value returned is a newly-created Element wrapping around the existing
1190 OO
.ui
.Element
.static.infuse = function ( idOrNode
) {
1191 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, false );
1192 // Verify that the type matches up.
1193 // FIXME: uncomment after T89721 is fixed (see T90929)
1195 if ( !( obj instanceof this['class'] ) ) {
1196 throw new Error( 'Infusion type mismatch!' );
1203 * Implementation helper for `infuse`; skips the type check and has an
1204 * extra property so that only the top-level invocation touches the DOM.
1206 * @param {string|HTMLElement|jQuery} idOrNode
1207 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
1208 * when the top-level widget of this infusion is inserted into DOM,
1209 * replacing the original node; or false for top-level invocation.
1210 * @return {OO.ui.Element}
1212 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, domPromise
) {
1213 // look for a cached result of a previous infusion.
1214 var id
, $elem
, data
, cls
, parts
, parent
, obj
, top
, state
;
1215 if ( typeof idOrNode
=== 'string' ) {
1217 $elem
= $( document
.getElementById( id
) );
1219 $elem
= $( idOrNode
);
1220 id
= $elem
.attr( 'id' );
1222 if ( !$elem
.length
) {
1223 throw new Error( 'Widget not found: ' + id
);
1225 data
= $elem
.data( 'ooui-infused' ) || $elem
[ 0 ].oouiInfused
;
1228 if ( data
=== true ) {
1229 throw new Error( 'Circular dependency! ' + id
);
1233 data
= $elem
.attr( 'data-ooui' );
1235 throw new Error( 'No infusion data found: ' + id
);
1238 data
= $.parseJSON( data
);
1242 if ( !( data
&& data
._
) ) {
1243 throw new Error( 'No valid infusion data found: ' + id
);
1245 if ( data
._
=== 'Tag' ) {
1246 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
1247 return new OO
.ui
.Element( { $element
: $elem
} );
1249 parts
= data
._
.split( '.' );
1250 cls
= OO
.getProp
.apply( OO
, [ window
].concat( parts
) );
1251 if ( cls
=== undefined ) {
1252 // The PHP output might be old and not including the "OO.ui" prefix
1253 // TODO: Remove this back-compat after next major release
1254 cls
= OO
.getProp
.apply( OO
, [ OO
.ui
].concat( parts
) );
1255 if ( cls
=== undefined ) {
1256 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
1260 // Verify that we're creating an OO.ui.Element instance
1261 parent
= cls
.parent
;
1263 while ( parent
!== undefined ) {
1264 if ( parent
=== OO
.ui
.Element
) {
1269 parent
= parent
.parent
;
1272 if ( parent
!== OO
.ui
.Element
) {
1273 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
1276 if ( domPromise
=== false ) {
1278 domPromise
= top
.promise();
1280 $elem
.data( 'ooui-infused', true ); // prevent loops
1281 data
.id
= id
; // implicit
1282 data
= OO
.copy( data
, null, function deserialize( value
) {
1283 if ( OO
.isPlainObject( value
) ) {
1285 return OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, domPromise
);
1288 return new OO
.ui
.HtmlSnippet( value
.html
);
1292 // allow widgets to reuse parts of the DOM
1293 data
= cls
.static.reusePreInfuseDOM( $elem
[ 0 ], data
);
1294 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
1295 state
= cls
.static.gatherPreInfuseState( $elem
[ 0 ], data
);
1297 // jscs:disable requireCapitalizedConstructors
1298 obj
= new cls( data
);
1299 // jscs:enable requireCapitalizedConstructors
1300 // now replace old DOM with this new DOM.
1302 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
1303 // so only mutate the DOM if we need to.
1304 if ( $elem
[ 0 ] !== obj
.$element
[ 0 ] ) {
1305 $elem
.replaceWith( obj
.$element
);
1306 // This element is now gone from the DOM, but if anyone is holding a reference to it,
1307 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
1308 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
1309 $elem
[ 0 ].oouiInfused
= obj
;
1313 obj
.$element
.data( 'ooui-infused', obj
);
1314 // set the 'data-ooui' attribute so we can identify infused widgets
1315 obj
.$element
.attr( 'data-ooui', '' );
1316 // restore dynamic state after the new element is inserted into DOM
1317 domPromise
.done( obj
.restorePreInfuseState
.bind( obj
, state
) );
1322 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
1324 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
1325 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
1326 * constructor, which will be given the enhanced config.
1329 * @param {HTMLElement} node
1330 * @param {Object} config
1333 OO
.ui
.Element
.static.reusePreInfuseDOM = function ( node
, config
) {
1338 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of a HTML DOM node
1339 * (and its children) that represent an Element of the same class and the given configuration,
1340 * generated by the PHP implementation.
1342 * This method is called just before `node` is detached from the DOM. The return value of this
1343 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
1344 * is inserted into DOM to replace `node`.
1347 * @param {HTMLElement} node
1348 * @param {Object} config
1351 OO
.ui
.Element
.static.gatherPreInfuseState = function () {
1356 * Get a jQuery function within a specific document.
1359 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1360 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1362 * @return {Function} Bound jQuery function
1364 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
1365 function wrapper( selector
) {
1366 return $( selector
, wrapper
.context
);
1369 wrapper
.context
= this.getDocument( context
);
1372 wrapper
.$iframe
= $iframe
;
1379 * Get the document of an element.
1382 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1383 * @return {HTMLDocument|null} Document object
1385 OO
.ui
.Element
.static.getDocument = function ( obj
) {
1386 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1387 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
1388 // Empty jQuery selections might have a context
1391 obj
.ownerDocument
||
1395 ( obj
.nodeType
=== 9 && obj
) ||
1400 * Get the window of an element or document.
1403 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1404 * @return {Window} Window object
1406 OO
.ui
.Element
.static.getWindow = function ( obj
) {
1407 var doc
= this.getDocument( obj
);
1409 // Standard Document.defaultView is IE9+
1410 return doc
.parentWindow
|| doc
.defaultView
;
1414 * Get the direction of an element or document.
1417 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1418 * @return {string} Text direction, either 'ltr' or 'rtl'
1420 OO
.ui
.Element
.static.getDir = function ( obj
) {
1423 if ( obj
instanceof jQuery
) {
1426 isDoc
= obj
.nodeType
=== 9;
1427 isWin
= obj
.document
!== undefined;
1428 if ( isDoc
|| isWin
) {
1434 return $( obj
).css( 'direction' );
1438 * Get the offset between two frames.
1440 * TODO: Make this function not use recursion.
1443 * @param {Window} from Window of the child frame
1444 * @param {Window} [to=window] Window of the parent frame
1445 * @param {Object} [offset] Offset to start with, used internally
1446 * @return {Object} Offset object, containing left and top properties
1448 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
1449 var i
, len
, frames
, frame
, rect
;
1455 offset
= { top
: 0, left
: 0 };
1457 if ( from.parent
=== from ) {
1461 // Get iframe element
1462 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
1463 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
1464 if ( frames
[ i
].contentWindow
=== from ) {
1465 frame
= frames
[ i
];
1470 // Recursively accumulate offset values
1472 rect
= frame
.getBoundingClientRect();
1473 offset
.left
+= rect
.left
;
1474 offset
.top
+= rect
.top
;
1475 if ( from !== to
) {
1476 this.getFrameOffset( from.parent
, offset
);
1483 * Get the offset between two elements.
1485 * The two elements may be in a different frame, but in that case the frame $element is in must
1486 * be contained in the frame $anchor is in.
1489 * @param {jQuery} $element Element whose position to get
1490 * @param {jQuery} $anchor Element to get $element's position relative to
1491 * @return {Object} Translated position coordinates, containing top and left properties
1493 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
1494 var iframe
, iframePos
,
1495 pos
= $element
.offset(),
1496 anchorPos
= $anchor
.offset(),
1497 elementDocument
= this.getDocument( $element
),
1498 anchorDocument
= this.getDocument( $anchor
);
1500 // If $element isn't in the same document as $anchor, traverse up
1501 while ( elementDocument
!== anchorDocument
) {
1502 iframe
= elementDocument
.defaultView
.frameElement
;
1504 throw new Error( '$element frame is not contained in $anchor frame' );
1506 iframePos
= $( iframe
).offset();
1507 pos
.left
+= iframePos
.left
;
1508 pos
.top
+= iframePos
.top
;
1509 elementDocument
= iframe
.ownerDocument
;
1511 pos
.left
-= anchorPos
.left
;
1512 pos
.top
-= anchorPos
.top
;
1517 * Get element border sizes.
1520 * @param {HTMLElement} el Element to measure
1521 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1523 OO
.ui
.Element
.static.getBorders = function ( el
) {
1524 var doc
= el
.ownerDocument
,
1526 // Standard Document.defaultView is IE9+
1527 win
= doc
.parentWindow
|| doc
.defaultView
,
1528 style
= win
&& win
.getComputedStyle
?
1529 win
.getComputedStyle( el
, null ) :
1531 // Standard getComputedStyle() is IE9+
1534 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
1535 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
1536 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
1537 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
1548 * Get dimensions of an element or window.
1551 * @param {HTMLElement|Window} el Element to measure
1552 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1554 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1556 doc
= el
.ownerDocument
|| el
.document
,
1558 // Standard Document.defaultView is IE9+
1559 win
= doc
.parentWindow
|| doc
.defaultView
;
1561 if ( win
=== el
|| el
=== doc
.documentElement
) {
1564 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1566 top
: $win
.scrollTop(),
1567 left
: $win
.scrollLeft()
1569 scrollbar
: { right
: 0, bottom
: 0 },
1573 bottom
: $win
.innerHeight(),
1574 right
: $win
.innerWidth()
1580 borders
: this.getBorders( el
),
1582 top
: $el
.scrollTop(),
1583 left
: $el
.scrollLeft()
1586 right
: $el
.innerWidth() - el
.clientWidth
,
1587 bottom
: $el
.innerHeight() - el
.clientHeight
1589 rect
: el
.getBoundingClientRect()
1595 * Get scrollable object parent
1597 * documentElement can't be used to get or set the scrollTop
1598 * property on Blink. Changing and testing its value lets us
1599 * use 'body' or 'documentElement' based on what is working.
1601 * https://code.google.com/p/chromium/issues/detail?id=303131
1604 * @param {HTMLElement} el Element to find scrollable parent for
1605 * @return {HTMLElement} Scrollable parent
1607 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1608 var scrollTop
, body
;
1610 if ( OO
.ui
.scrollableElement
=== undefined ) {
1611 body
= el
.ownerDocument
.body
;
1612 scrollTop
= body
.scrollTop
;
1615 if ( body
.scrollTop
=== 1 ) {
1616 body
.scrollTop
= scrollTop
;
1617 OO
.ui
.scrollableElement
= 'body';
1619 OO
.ui
.scrollableElement
= 'documentElement';
1623 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1627 * Get closest scrollable container.
1629 * Traverses up until either a scrollable element or the root is reached, in which case the window
1633 * @param {HTMLElement} el Element to find scrollable container for
1634 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1635 * @return {HTMLElement} Closest scrollable container
1637 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1639 // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
1640 props
= [ 'overflow-x', 'overflow-y' ],
1641 $parent
= $( el
).parent();
1643 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1644 props
= [ 'overflow-' + dimension
];
1647 while ( $parent
.length
) {
1648 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1649 return $parent
[ 0 ];
1653 val
= $parent
.css( props
[ i
] );
1654 if ( val
=== 'auto' || val
=== 'scroll' ) {
1655 return $parent
[ 0 ];
1658 $parent
= $parent
.parent();
1660 return this.getDocument( el
).body
;
1664 * Scroll element into view.
1667 * @param {HTMLElement} el Element to scroll into view
1668 * @param {Object} [config] Configuration options
1669 * @param {string} [config.duration] jQuery animation duration value
1670 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1671 * to scroll in both directions
1672 * @param {Function} [config.complete] Function to call when scrolling completes
1674 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1675 var rel
, anim
, callback
, sc
, $sc
, eld
, scd
, $win
;
1677 // Configuration initialization
1678 config
= config
|| {};
1681 callback
= typeof config
.complete
=== 'function' && config
.complete
;
1682 sc
= this.getClosestScrollableContainer( el
, config
.direction
);
1684 eld
= this.getDimensions( el
);
1685 scd
= this.getDimensions( sc
);
1686 $win
= $( this.getWindow( el
) );
1688 // Compute the distances between the edges of el and the edges of the scroll viewport
1689 if ( $sc
.is( 'html, body' ) ) {
1690 // If the scrollable container is the root, this is easy
1693 bottom
: $win
.innerHeight() - eld
.rect
.bottom
,
1694 left
: eld
.rect
.left
,
1695 right
: $win
.innerWidth() - eld
.rect
.right
1698 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1700 top
: eld
.rect
.top
- ( scd
.rect
.top
+ scd
.borders
.top
),
1701 bottom
: scd
.rect
.bottom
- scd
.borders
.bottom
- scd
.scrollbar
.bottom
- eld
.rect
.bottom
,
1702 left
: eld
.rect
.left
- ( scd
.rect
.left
+ scd
.borders
.left
),
1703 right
: scd
.rect
.right
- scd
.borders
.right
- scd
.scrollbar
.right
- eld
.rect
.right
1707 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1708 if ( rel
.top
< 0 ) {
1709 anim
.scrollTop
= scd
.scroll
.top
+ rel
.top
;
1710 } else if ( rel
.top
> 0 && rel
.bottom
< 0 ) {
1711 anim
.scrollTop
= scd
.scroll
.top
+ Math
.min( rel
.top
, -rel
.bottom
);
1714 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1715 if ( rel
.left
< 0 ) {
1716 anim
.scrollLeft
= scd
.scroll
.left
+ rel
.left
;
1717 } else if ( rel
.left
> 0 && rel
.right
< 0 ) {
1718 anim
.scrollLeft
= scd
.scroll
.left
+ Math
.min( rel
.left
, -rel
.right
);
1721 if ( !$.isEmptyObject( anim
) ) {
1722 $sc
.stop( true ).animate( anim
, config
.duration
|| 'fast' );
1724 $sc
.queue( function ( next
) {
1737 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1738 * and reserve space for them, because it probably doesn't.
1740 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1741 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1742 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1743 * and then reattach (or show) them back.
1746 * @param {HTMLElement} el Element to reconsider the scrollbars on
1748 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1749 var i
, len
, scrollLeft
, scrollTop
, nodes
= [];
1750 // Save scroll position
1751 scrollLeft
= el
.scrollLeft
;
1752 scrollTop
= el
.scrollTop
;
1753 // Detach all children
1754 while ( el
.firstChild
) {
1755 nodes
.push( el
.firstChild
);
1756 el
.removeChild( el
.firstChild
);
1759 void el
.offsetHeight
;
1760 // Reattach all children
1761 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1762 el
.appendChild( nodes
[ i
] );
1764 // Restore scroll position (no-op if scrollbars disappeared)
1765 el
.scrollLeft
= scrollLeft
;
1766 el
.scrollTop
= scrollTop
;
1772 * Toggle visibility of an element.
1774 * @param {boolean} [show] Make element visible, omit to toggle visibility
1778 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1779 show
= show
=== undefined ? !this.visible
: !!show
;
1781 if ( show
!== this.isVisible() ) {
1782 this.visible
= show
;
1783 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1784 this.emit( 'toggle', show
);
1791 * Check if element is visible.
1793 * @return {boolean} element is visible
1795 OO
.ui
.Element
.prototype.isVisible = function () {
1796 return this.visible
;
1802 * @return {Mixed} Element data
1804 OO
.ui
.Element
.prototype.getData = function () {
1811 * @param {Mixed} Element data
1814 OO
.ui
.Element
.prototype.setData = function ( data
) {
1820 * Check if element supports one or more methods.
1822 * @param {string|string[]} methods Method or list of methods to check
1823 * @return {boolean} All methods are supported
1825 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1829 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1830 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1831 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1836 return methods
.length
=== support
;
1840 * Update the theme-provided classes.
1842 * @localdoc This is called in element mixins and widget classes any time state changes.
1843 * Updating is debounced, minimizing overhead of changing multiple attributes and
1844 * guaranteeing that theme updates do not occur within an element's constructor
1846 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1847 this.debouncedUpdateThemeClassesHandler();
1852 * @localdoc This method is called directly from the QUnit tests instead of #updateThemeClasses, to
1853 * make them synchronous.
1855 OO
.ui
.Element
.prototype.debouncedUpdateThemeClasses = function () {
1856 OO
.ui
.theme
.updateElementClasses( this );
1860 * Get the HTML tag name.
1862 * Override this method to base the result on instance information.
1864 * @return {string} HTML tag name
1866 OO
.ui
.Element
.prototype.getTagName = function () {
1867 return this.constructor.static.tagName
;
1871 * Check if the element is attached to the DOM
1872 * @return {boolean} The element is attached to the DOM
1874 OO
.ui
.Element
.prototype.isElementAttached = function () {
1875 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1879 * Get the DOM document.
1881 * @return {HTMLDocument} Document object
1883 OO
.ui
.Element
.prototype.getElementDocument = function () {
1884 // Don't cache this in other ways either because subclasses could can change this.$element
1885 return OO
.ui
.Element
.static.getDocument( this.$element
);
1889 * Get the DOM window.
1891 * @return {Window} Window object
1893 OO
.ui
.Element
.prototype.getElementWindow = function () {
1894 return OO
.ui
.Element
.static.getWindow( this.$element
);
1898 * Get closest scrollable container.
1900 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1901 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1905 * Get group element is in.
1907 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1909 OO
.ui
.Element
.prototype.getElementGroup = function () {
1910 return this.elementGroup
;
1914 * Set group element is in.
1916 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1919 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1920 this.elementGroup
= group
;
1925 * Scroll element into view.
1927 * @param {Object} [config] Configuration options
1929 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1930 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1934 * Restore the pre-infusion dynamic state for this widget.
1936 * This method is called after #$element has been inserted into DOM. The parameter is the return
1937 * value of #gatherPreInfuseState.
1940 * @param {Object} state
1942 OO
.ui
.Element
.prototype.restorePreInfuseState = function () {
1946 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1947 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1948 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1949 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1950 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1954 * @extends OO.ui.Element
1955 * @mixins OO.EventEmitter
1958 * @param {Object} [config] Configuration options
1960 OO
.ui
.Layout
= function OoUiLayout( config
) {
1961 // Configuration initialization
1962 config
= config
|| {};
1964 // Parent constructor
1965 OO
.ui
.Layout
.parent
.call( this, config
);
1967 // Mixin constructors
1968 OO
.EventEmitter
.call( this );
1971 this.$element
.addClass( 'oo-ui-layout' );
1976 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1977 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1980 * Widgets are compositions of one or more OOjs UI elements that users can both view
1981 * and interact with. All widgets can be configured and modified via a standard API,
1982 * and their state can change dynamically according to a model.
1986 * @extends OO.ui.Element
1987 * @mixins OO.EventEmitter
1990 * @param {Object} [config] Configuration options
1991 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1992 * appearance reflects this state.
1994 OO
.ui
.Widget
= function OoUiWidget( config
) {
1995 // Initialize config
1996 config
= $.extend( { disabled
: false }, config
);
1998 // Parent constructor
1999 OO
.ui
.Widget
.parent
.call( this, config
);
2001 // Mixin constructors
2002 OO
.EventEmitter
.call( this );
2005 this.disabled
= null;
2006 this.wasDisabled
= null;
2009 this.$element
.addClass( 'oo-ui-widget' );
2010 this.setDisabled( !!config
.disabled
);
2015 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
2016 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
2018 /* Static Properties */
2021 * Whether this widget will behave reasonably when wrapped in a HTML `<label>`. If this is true,
2022 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
2027 * @property {boolean}
2029 OO
.ui
.Widget
.static.supportsSimpleLabel
= false;
2036 * A 'disable' event is emitted when the disabled state of the widget changes
2037 * (i.e. on disable **and** enable).
2039 * @param {boolean} disabled Widget is disabled
2045 * A 'toggle' event is emitted when the visibility of the widget changes.
2047 * @param {boolean} visible Widget is visible
2053 * Check if the widget is disabled.
2055 * @return {boolean} Widget is disabled
2057 OO
.ui
.Widget
.prototype.isDisabled = function () {
2058 return this.disabled
;
2062 * Set the 'disabled' state of the widget.
2064 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
2066 * @param {boolean} disabled Disable widget
2069 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
2072 this.disabled
= !!disabled
;
2073 isDisabled
= this.isDisabled();
2074 if ( isDisabled
!== this.wasDisabled
) {
2075 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
2076 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
2077 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
2078 this.emit( 'disable', isDisabled
);
2079 this.updateThemeClasses();
2081 this.wasDisabled
= isDisabled
;
2087 * Update the disabled state, in case of changes in parent widget.
2091 OO
.ui
.Widget
.prototype.updateDisabled = function () {
2092 this.setDisabled( this.disabled
);
2097 * A window is a container for elements that are in a child frame. They are used with
2098 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
2099 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
2100 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
2101 * the window manager will choose a sensible fallback.
2103 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
2104 * different processes are executed:
2106 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
2107 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
2110 * - {@link #getSetupProcess} method is called and its result executed
2111 * - {@link #getReadyProcess} method is called and its result executed
2113 * **opened**: The window is now open
2115 * **closing**: The closing stage begins when the window manager's
2116 * {@link OO.ui.WindowManager#closeWindow closeWindow}
2117 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
2119 * - {@link #getHoldProcess} method is called and its result executed
2120 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
2122 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
2123 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
2124 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
2125 * processing can complete. Always assume window processes are executed asynchronously.
2127 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2129 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
2133 * @extends OO.ui.Element
2134 * @mixins OO.EventEmitter
2137 * @param {Object} [config] Configuration options
2138 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
2139 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
2141 OO
.ui
.Window
= function OoUiWindow( config
) {
2142 // Configuration initialization
2143 config
= config
|| {};
2145 // Parent constructor
2146 OO
.ui
.Window
.parent
.call( this, config
);
2148 // Mixin constructors
2149 OO
.EventEmitter
.call( this );
2152 this.manager
= null;
2153 this.size
= config
.size
|| this.constructor.static.size
;
2154 this.$frame
= $( '<div>' );
2155 this.$overlay
= $( '<div>' );
2156 this.$content
= $( '<div>' );
2158 this.$focusTrapBefore
= $( '<div>' ).prop( 'tabIndex', 0 );
2159 this.$focusTrapAfter
= $( '<div>' ).prop( 'tabIndex', 0 );
2160 this.$focusTraps
= this.$focusTrapBefore
.add( this.$focusTrapAfter
);
2163 this.$overlay
.addClass( 'oo-ui-window-overlay' );
2165 .addClass( 'oo-ui-window-content' )
2166 .attr( 'tabindex', 0 );
2168 .addClass( 'oo-ui-window-frame' )
2169 .append( this.$focusTrapBefore
, this.$content
, this.$focusTrapAfter
);
2172 .addClass( 'oo-ui-window' )
2173 .append( this.$frame
, this.$overlay
);
2175 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
2176 // that reference properties not initialized at that time of parent class construction
2177 // TODO: Find a better way to handle post-constructor setup
2178 this.visible
= false;
2179 this.$element
.addClass( 'oo-ui-element-hidden' );
2184 OO
.inheritClass( OO
.ui
.Window
, OO
.ui
.Element
);
2185 OO
.mixinClass( OO
.ui
.Window
, OO
.EventEmitter
);
2187 /* Static Properties */
2190 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
2192 * The static size is used if no #size is configured during construction.
2196 * @property {string}
2198 OO
.ui
.Window
.static.size
= 'medium';
2203 * Handle mouse down events.
2206 * @param {jQuery.Event} e Mouse down event
2208 OO
.ui
.Window
.prototype.onMouseDown = function ( e
) {
2209 // Prevent clicking on the click-block from stealing focus
2210 if ( e
.target
=== this.$element
[ 0 ] ) {
2216 * Check if the window has been initialized.
2218 * Initialization occurs when a window is added to a manager.
2220 * @return {boolean} Window has been initialized
2222 OO
.ui
.Window
.prototype.isInitialized = function () {
2223 return !!this.manager
;
2227 * Check if the window is visible.
2229 * @return {boolean} Window is visible
2231 OO
.ui
.Window
.prototype.isVisible = function () {
2232 return this.visible
;
2236 * Check if the window is opening.
2238 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
2241 * @return {boolean} Window is opening
2243 OO
.ui
.Window
.prototype.isOpening = function () {
2244 return this.manager
.isOpening( this );
2248 * Check if the window is closing.
2250 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
2252 * @return {boolean} Window is closing
2254 OO
.ui
.Window
.prototype.isClosing = function () {
2255 return this.manager
.isClosing( this );
2259 * Check if the window is opened.
2261 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
2263 * @return {boolean} Window is opened
2265 OO
.ui
.Window
.prototype.isOpened = function () {
2266 return this.manager
.isOpened( this );
2270 * Get the window manager.
2272 * All windows must be attached to a window manager, which is used to open
2273 * and close the window and control its presentation.
2275 * @return {OO.ui.WindowManager} Manager of window
2277 OO
.ui
.Window
.prototype.getManager = function () {
2278 return this.manager
;
2282 * Get the symbolic name of the window size (e.g., `small` or `medium`).
2284 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
2286 OO
.ui
.Window
.prototype.getSize = function () {
2287 var viewport
= OO
.ui
.Element
.static.getDimensions( this.getElementWindow() ),
2288 sizes
= this.manager
.constructor.static.sizes
,
2291 if ( !sizes
[ size
] ) {
2292 size
= this.manager
.constructor.static.defaultSize
;
2294 if ( size
!== 'full' && viewport
.rect
.right
- viewport
.rect
.left
< sizes
[ size
].width
) {
2302 * Get the size properties associated with the current window size
2304 * @return {Object} Size properties
2306 OO
.ui
.Window
.prototype.getSizeProperties = function () {
2307 return this.manager
.constructor.static.sizes
[ this.getSize() ];
2311 * Disable transitions on window's frame for the duration of the callback function, then enable them
2315 * @param {Function} callback Function to call while transitions are disabled
2317 OO
.ui
.Window
.prototype.withoutSizeTransitions = function ( callback
) {
2318 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2319 // Disable transitions first, otherwise we'll get values from when the window was animating.
2321 styleObj
= this.$frame
[ 0 ].style
;
2322 oldTransition
= styleObj
.transition
|| styleObj
.OTransition
|| styleObj
.MsTransition
||
2323 styleObj
.MozTransition
|| styleObj
.WebkitTransition
;
2324 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
2325 styleObj
.MozTransition
= styleObj
.WebkitTransition
= 'none';
2327 // Force reflow to make sure the style changes done inside callback really are not transitioned
2328 this.$frame
.height();
2329 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
2330 styleObj
.MozTransition
= styleObj
.WebkitTransition
= oldTransition
;
2334 * Get the height of the full window contents (i.e., the window head, body and foot together).
2336 * What consistitutes the head, body, and foot varies depending on the window type.
2337 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
2338 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
2339 * and special actions in the head, and dialog content in the body.
2341 * To get just the height of the dialog body, use the #getBodyHeight method.
2343 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
2345 OO
.ui
.Window
.prototype.getContentHeight = function () {
2348 bodyStyleObj
= this.$body
[ 0 ].style
,
2349 frameStyleObj
= this.$frame
[ 0 ].style
;
2351 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2352 // Disable transitions first, otherwise we'll get values from when the window was animating.
2353 this.withoutSizeTransitions( function () {
2354 var oldHeight
= frameStyleObj
.height
,
2355 oldPosition
= bodyStyleObj
.position
;
2356 frameStyleObj
.height
= '1px';
2357 // Force body to resize to new width
2358 bodyStyleObj
.position
= 'relative';
2359 bodyHeight
= win
.getBodyHeight();
2360 frameStyleObj
.height
= oldHeight
;
2361 bodyStyleObj
.position
= oldPosition
;
2365 // Add buffer for border
2366 ( this.$frame
.outerHeight() - this.$frame
.innerHeight() ) +
2367 // Use combined heights of children
2368 ( this.$head
.outerHeight( true ) + bodyHeight
+ this.$foot
.outerHeight( true ) )
2373 * Get the height of the window body.
2375 * To get the height of the full window contents (the window body, head, and foot together),
2376 * use #getContentHeight.
2378 * When this function is called, the window will temporarily have been resized
2379 * to height=1px, so .scrollHeight measurements can be taken accurately.
2381 * @return {number} Height of the window body in pixels
2383 OO
.ui
.Window
.prototype.getBodyHeight = function () {
2384 return this.$body
[ 0 ].scrollHeight
;
2388 * Get the directionality of the frame (right-to-left or left-to-right).
2390 * @return {string} Directionality: `'ltr'` or `'rtl'`
2392 OO
.ui
.Window
.prototype.getDir = function () {
2393 return OO
.ui
.Element
.static.getDir( this.$content
) || 'ltr';
2397 * Get the 'setup' process.
2399 * The setup process is used to set up a window for use in a particular context,
2400 * based on the `data` argument. This method is called during the opening phase of the window’s
2403 * Override this method to add additional steps to the ‘setup’ process the parent method provides
2404 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2407 * To add window content that persists between openings, you may wish to use the #initialize method
2411 * @param {Object} [data] Window opening data
2412 * @return {OO.ui.Process} Setup process
2414 OO
.ui
.Window
.prototype.getSetupProcess = function () {
2415 return new OO
.ui
.Process();
2419 * Get the ‘ready’ process.
2421 * The ready process is used to ready a window for use in a particular
2422 * context, based on the `data` argument. This method is called during the opening phase of
2423 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2425 * Override this method to add additional steps to the ‘ready’ process the parent method
2426 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2427 * methods of OO.ui.Process.
2430 * @param {Object} [data] Window opening data
2431 * @return {OO.ui.Process} Ready process
2433 OO
.ui
.Window
.prototype.getReadyProcess = function () {
2434 return new OO
.ui
.Process();
2438 * Get the 'hold' process.
2440 * The hold proccess is used to keep a window from being used in a particular context,
2441 * based on the `data` argument. This method is called during the closing phase of the window’s
2444 * Override this method to add additional steps to the 'hold' process the parent method provides
2445 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2449 * @param {Object} [data] Window closing data
2450 * @return {OO.ui.Process} Hold process
2452 OO
.ui
.Window
.prototype.getHoldProcess = function () {
2453 return new OO
.ui
.Process();
2457 * Get the ‘teardown’ process.
2459 * The teardown process is used to teardown a window after use. During teardown,
2460 * user interactions within the window are conveyed and the window is closed, based on the `data`
2461 * argument. This method is called during the closing phase of the window’s lifecycle.
2463 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2464 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2468 * @param {Object} [data] Window closing data
2469 * @return {OO.ui.Process} Teardown process
2471 OO
.ui
.Window
.prototype.getTeardownProcess = function () {
2472 return new OO
.ui
.Process();
2476 * Set the window manager.
2478 * This will cause the window to initialize. Calling it more than once will cause an error.
2480 * @param {OO.ui.WindowManager} manager Manager for this window
2481 * @throws {Error} An error is thrown if the method is called more than once
2484 OO
.ui
.Window
.prototype.setManager = function ( manager
) {
2485 if ( this.manager
) {
2486 throw new Error( 'Cannot set window manager, window already has a manager' );
2489 this.manager
= manager
;
2496 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2498 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2502 OO
.ui
.Window
.prototype.setSize = function ( size
) {
2509 * Update the window size.
2511 * @throws {Error} An error is thrown if the window is not attached to a window manager
2514 OO
.ui
.Window
.prototype.updateSize = function () {
2515 if ( !this.manager
) {
2516 throw new Error( 'Cannot update window size, must be attached to a manager' );
2519 this.manager
.updateWindowSize( this );
2525 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2526 * when the window is opening. In general, setDimensions should not be called directly.
2528 * To set the size of the window, use the #setSize method.
2530 * @param {Object} dim CSS dimension properties
2531 * @param {string|number} [dim.width] Width
2532 * @param {string|number} [dim.minWidth] Minimum width
2533 * @param {string|number} [dim.maxWidth] Maximum width
2534 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2535 * @param {string|number} [dim.minWidth] Minimum height
2536 * @param {string|number} [dim.maxWidth] Maximum height
2539 OO
.ui
.Window
.prototype.setDimensions = function ( dim
) {
2542 styleObj
= this.$frame
[ 0 ].style
;
2544 // Calculate the height we need to set using the correct width
2545 if ( dim
.height
=== undefined ) {
2546 this.withoutSizeTransitions( function () {
2547 var oldWidth
= styleObj
.width
;
2548 win
.$frame
.css( 'width', dim
.width
|| '' );
2549 height
= win
.getContentHeight();
2550 styleObj
.width
= oldWidth
;
2553 height
= dim
.height
;
2557 width
: dim
.width
|| '',
2558 minWidth
: dim
.minWidth
|| '',
2559 maxWidth
: dim
.maxWidth
|| '',
2560 height
: height
|| '',
2561 minHeight
: dim
.minHeight
|| '',
2562 maxHeight
: dim
.maxHeight
|| ''
2569 * Initialize window contents.
2571 * Before the window is opened for the first time, #initialize is called so that content that
2572 * persists between openings can be added to the window.
2574 * To set up a window with new content each time the window opens, use #getSetupProcess.
2576 * @throws {Error} An error is thrown if the window is not attached to a window manager
2579 OO
.ui
.Window
.prototype.initialize = function () {
2580 if ( !this.manager
) {
2581 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2585 this.$head
= $( '<div>' );
2586 this.$body
= $( '<div>' );
2587 this.$foot
= $( '<div>' );
2588 this.$document
= $( this.getElementDocument() );
2591 this.$element
.on( 'mousedown', this.onMouseDown
.bind( this ) );
2594 this.$head
.addClass( 'oo-ui-window-head' );
2595 this.$body
.addClass( 'oo-ui-window-body' );
2596 this.$foot
.addClass( 'oo-ui-window-foot' );
2597 this.$content
.append( this.$head
, this.$body
, this.$foot
);
2603 * Called when someone tries to focus the hidden element at the end of the dialog.
2604 * Sends focus back to the start of the dialog.
2606 * @param {jQuery.Event} event Focus event
2608 OO
.ui
.Window
.prototype.onFocusTrapFocused = function ( event
) {
2609 if ( this.$focusTrapBefore
.is( event
.target
) ) {
2610 OO
.ui
.findFocusable( this.$content
, true ).focus();
2612 // this.$content is the part of the focus cycle, and is the first focusable element
2613 this.$content
.focus();
2620 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2621 * method, which returns a promise resolved when the window is done opening.
2623 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2625 * @param {Object} [data] Window opening data
2626 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2627 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2628 * value is a new promise, which is resolved when the window begins closing.
2629 * @throws {Error} An error is thrown if the window is not attached to a window manager
2631 OO
.ui
.Window
.prototype.open = function ( data
) {
2632 if ( !this.manager
) {
2633 throw new Error( 'Cannot open window, must be attached to a manager' );
2636 return this.manager
.openWindow( this, data
);
2642 * This method is a wrapper around a call to the window
2643 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2644 * which returns a closing promise resolved when the window is done closing.
2646 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2647 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2648 * the window closes.
2650 * @param {Object} [data] Window closing data
2651 * @return {jQuery.Promise} Promise resolved when window is closed
2652 * @throws {Error} An error is thrown if the window is not attached to a window manager
2654 OO
.ui
.Window
.prototype.close = function ( data
) {
2655 if ( !this.manager
) {
2656 throw new Error( 'Cannot close window, must be attached to a manager' );
2659 return this.manager
.closeWindow( this, data
);
2665 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2668 * @param {Object} [data] Window opening data
2669 * @return {jQuery.Promise} Promise resolved when window is setup
2671 OO
.ui
.Window
.prototype.setup = function ( data
) {
2673 deferred
= $.Deferred();
2675 this.toggle( true );
2677 this.focusTrapHandler
= OO
.ui
.bind( this.onFocusTrapFocused
, this );
2678 this.$focusTraps
.on( 'focus', this.focusTrapHandler
);
2680 this.getSetupProcess( data
).execute().done( function () {
2681 // Force redraw by asking the browser to measure the elements' widths
2682 win
.$element
.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2683 win
.$content
.addClass( 'oo-ui-window-content-setup' ).width();
2687 return deferred
.promise();
2693 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2696 * @param {Object} [data] Window opening data
2697 * @return {jQuery.Promise} Promise resolved when window is ready
2699 OO
.ui
.Window
.prototype.ready = function ( data
) {
2701 deferred
= $.Deferred();
2703 this.$content
.focus();
2704 this.getReadyProcess( data
).execute().done( function () {
2705 // Force redraw by asking the browser to measure the elements' widths
2706 win
.$element
.addClass( 'oo-ui-window-ready' ).width();
2707 win
.$content
.addClass( 'oo-ui-window-content-ready' ).width();
2711 return deferred
.promise();
2717 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2720 * @param {Object} [data] Window closing data
2721 * @return {jQuery.Promise} Promise resolved when window is held
2723 OO
.ui
.Window
.prototype.hold = function ( data
) {
2725 deferred
= $.Deferred();
2727 this.getHoldProcess( data
).execute().done( function () {
2728 // Get the focused element within the window's content
2729 var $focus
= win
.$content
.find( OO
.ui
.Element
.static.getDocument( win
.$content
).activeElement
);
2731 // Blur the focused element
2732 if ( $focus
.length
) {
2736 // Force redraw by asking the browser to measure the elements' widths
2737 win
.$element
.removeClass( 'oo-ui-window-ready' ).width();
2738 win
.$content
.removeClass( 'oo-ui-window-content-ready' ).width();
2742 return deferred
.promise();
2748 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2751 * @param {Object} [data] Window closing data
2752 * @return {jQuery.Promise} Promise resolved when window is torn down
2754 OO
.ui
.Window
.prototype.teardown = function ( data
) {
2757 return this.getTeardownProcess( data
).execute()
2758 .done( function () {
2759 // Force redraw by asking the browser to measure the elements' widths
2760 win
.$element
.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2761 win
.$content
.removeClass( 'oo-ui-window-content-setup' ).width();
2762 win
.$focusTraps
.off( 'focus', win
.focusTrapHandler
);
2763 win
.toggle( false );
2768 * The Dialog class serves as the base class for the other types of dialogs.
2769 * Unless extended to include controls, the rendered dialog box is a simple window
2770 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2771 * which opens, closes, and controls the presentation of the window. See the
2772 * [OOjs UI documentation on MediaWiki] [1] for more information.
2775 * // A simple dialog window.
2776 * function MyDialog( config ) {
2777 * MyDialog.parent.call( this, config );
2779 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2780 * MyDialog.prototype.initialize = function () {
2781 * MyDialog.parent.prototype.initialize.call( this );
2782 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2783 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2784 * this.$body.append( this.content.$element );
2786 * MyDialog.prototype.getBodyHeight = function () {
2787 * return this.content.$element.outerHeight( true );
2789 * var myDialog = new MyDialog( {
2792 * // Create and append a window manager, which opens and closes the window.
2793 * var windowManager = new OO.ui.WindowManager();
2794 * $( 'body' ).append( windowManager.$element );
2795 * windowManager.addWindows( [ myDialog ] );
2796 * // Open the window!
2797 * windowManager.openWindow( myDialog );
2799 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2803 * @extends OO.ui.Window
2804 * @mixins OO.ui.mixin.PendingElement
2807 * @param {Object} [config] Configuration options
2809 OO
.ui
.Dialog
= function OoUiDialog( config
) {
2810 // Parent constructor
2811 OO
.ui
.Dialog
.parent
.call( this, config
);
2813 // Mixin constructors
2814 OO
.ui
.mixin
.PendingElement
.call( this );
2817 this.actions
= new OO
.ui
.ActionSet();
2818 this.attachedActions
= [];
2819 this.currentAction
= null;
2820 this.onDialogKeyDownHandler
= this.onDialogKeyDown
.bind( this );
2823 this.actions
.connect( this, {
2824 click
: 'onActionClick',
2825 resize
: 'onActionResize',
2826 change
: 'onActionsChange'
2831 .addClass( 'oo-ui-dialog' )
2832 .attr( 'role', 'dialog' );
2837 OO
.inheritClass( OO
.ui
.Dialog
, OO
.ui
.Window
);
2838 OO
.mixinClass( OO
.ui
.Dialog
, OO
.ui
.mixin
.PendingElement
);
2840 /* Static Properties */
2843 * Symbolic name of dialog.
2845 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2846 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2848 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2853 * @property {string}
2855 OO
.ui
.Dialog
.static.name
= '';
2860 * The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function
2861 * that will produce a Label node or string. The title can also be specified with data passed to the
2862 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2867 * @property {jQuery|string|Function}
2869 OO
.ui
.Dialog
.static.title
= '';
2872 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2874 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2875 * value will be overriden.
2877 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2881 * @property {Object[]}
2883 OO
.ui
.Dialog
.static.actions
= [];
2886 * Close the dialog when the 'Esc' key is pressed.
2891 * @property {boolean}
2893 OO
.ui
.Dialog
.static.escapable
= true;
2898 * Handle frame document key down events.
2901 * @param {jQuery.Event} e Key down event
2903 OO
.ui
.Dialog
.prototype.onDialogKeyDown = function ( e
) {
2904 if ( e
.which
=== OO
.ui
.Keys
.ESCAPE
) {
2907 e
.stopPropagation();
2912 * Handle action resized events.
2915 * @param {OO.ui.ActionWidget} action Action that was resized
2917 OO
.ui
.Dialog
.prototype.onActionResize = function () {
2918 // Override in subclass
2922 * Handle action click events.
2925 * @param {OO.ui.ActionWidget} action Action that was clicked
2927 OO
.ui
.Dialog
.prototype.onActionClick = function ( action
) {
2928 if ( !this.isPending() ) {
2929 this.executeAction( action
.getAction() );
2934 * Handle actions change event.
2938 OO
.ui
.Dialog
.prototype.onActionsChange = function () {
2939 this.detachActions();
2940 if ( !this.isClosing() ) {
2941 this.attachActions();
2946 * Get the set of actions used by the dialog.
2948 * @return {OO.ui.ActionSet}
2950 OO
.ui
.Dialog
.prototype.getActions = function () {
2951 return this.actions
;
2955 * Get a process for taking action.
2957 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2958 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2959 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2962 * @param {string} [action] Symbolic name of action
2963 * @return {OO.ui.Process} Action process
2965 OO
.ui
.Dialog
.prototype.getActionProcess = function ( action
) {
2966 return new OO
.ui
.Process()
2967 .next( function () {
2969 // An empty action always closes the dialog without data, which should always be
2970 // safe and make no changes
2979 * @param {Object} [data] Dialog opening data
2980 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2981 * the {@link #static-title static title}
2982 * @param {Object[]} [data.actions] List of configuration options for each
2983 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2985 OO
.ui
.Dialog
.prototype.getSetupProcess = function ( data
) {
2989 return OO
.ui
.Dialog
.parent
.prototype.getSetupProcess
.call( this, data
)
2990 .next( function () {
2991 var config
= this.constructor.static,
2992 actions
= data
.actions
!== undefined ? data
.actions
: config
.actions
;
2994 this.title
.setLabel(
2995 data
.title
!== undefined ? data
.title
: this.constructor.static.title
2997 this.actions
.add( this.getActionWidgets( actions
) );
2999 if ( this.constructor.static.escapable
) {
3000 this.$element
.on( 'keydown', this.onDialogKeyDownHandler
);
3008 OO
.ui
.Dialog
.prototype.getTeardownProcess = function ( data
) {
3010 return OO
.ui
.Dialog
.parent
.prototype.getTeardownProcess
.call( this, data
)
3011 .first( function () {
3012 if ( this.constructor.static.escapable
) {
3013 this.$element
.off( 'keydown', this.onDialogKeyDownHandler
);
3016 this.actions
.clear();
3017 this.currentAction
= null;
3024 OO
.ui
.Dialog
.prototype.initialize = function () {
3028 OO
.ui
.Dialog
.parent
.prototype.initialize
.call( this );
3030 titleId
= OO
.ui
.generateElementId();
3033 this.title
= new OO
.ui
.LabelWidget( {
3038 this.$content
.addClass( 'oo-ui-dialog-content' );
3039 this.$element
.attr( 'aria-labelledby', titleId
);
3040 this.setPendingElement( this.$head
);
3044 * Get action widgets from a list of configs
3046 * @param {Object[]} actions Action widget configs
3047 * @return {OO.ui.ActionWidget[]} Action widgets
3049 OO
.ui
.Dialog
.prototype.getActionWidgets = function ( actions
) {
3050 var i
, len
, widgets
= [];
3051 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
3053 new OO
.ui
.ActionWidget( actions
[ i
] )
3060 * Attach action actions.
3064 OO
.ui
.Dialog
.prototype.attachActions = function () {
3065 // Remember the list of potentially attached actions
3066 this.attachedActions
= this.actions
.get();
3070 * Detach action actions.
3075 OO
.ui
.Dialog
.prototype.detachActions = function () {
3078 // Detach all actions that may have been previously attached
3079 for ( i
= 0, len
= this.attachedActions
.length
; i
< len
; i
++ ) {
3080 this.attachedActions
[ i
].$element
.detach();
3082 this.attachedActions
= [];
3086 * Execute an action.
3088 * @param {string} action Symbolic name of action to execute
3089 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
3091 OO
.ui
.Dialog
.prototype.executeAction = function ( action
) {
3093 this.currentAction
= action
;
3094 return this.getActionProcess( action
).execute()
3095 .always( this.popPending
.bind( this ) );
3099 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
3100 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
3101 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
3102 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
3103 * pertinent data and reused.
3105 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
3106 * `opened`, and `closing`, which represent the primary stages of the cycle:
3108 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
3109 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
3111 * - an `opening` event is emitted with an `opening` promise
3112 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
3113 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
3114 * window and its result executed
3115 * - a `setup` progress notification is emitted from the `opening` promise
3116 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
3117 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
3118 * window and its result executed
3119 * - a `ready` progress notification is emitted from the `opening` promise
3120 * - the `opening` promise is resolved with an `opened` promise
3122 * **Opened**: the window is now open.
3124 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
3125 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
3126 * to close the window.
3128 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
3129 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
3130 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
3131 * window and its result executed
3132 * - a `hold` progress notification is emitted from the `closing` promise
3133 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
3134 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
3135 * window and its result executed
3136 * - a `teardown` progress notification is emitted from the `closing` promise
3137 * - the `closing` promise is resolved. The window is now closed
3139 * See the [OOjs UI documentation on MediaWiki][1] for more information.
3141 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3144 * @extends OO.ui.Element
3145 * @mixins OO.EventEmitter
3148 * @param {Object} [config] Configuration options
3149 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
3150 * Note that window classes that are instantiated with a factory must have
3151 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
3152 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
3154 OO
.ui
.WindowManager
= function OoUiWindowManager( config
) {
3155 // Configuration initialization
3156 config
= config
|| {};
3158 // Parent constructor
3159 OO
.ui
.WindowManager
.parent
.call( this, config
);
3161 // Mixin constructors
3162 OO
.EventEmitter
.call( this );
3165 this.factory
= config
.factory
;
3166 this.modal
= config
.modal
=== undefined || !!config
.modal
;
3168 this.opening
= null;
3170 this.closing
= null;
3171 this.preparingToOpen
= null;
3172 this.preparingToClose
= null;
3173 this.currentWindow
= null;
3174 this.globalEvents
= false;
3175 this.$ariaHidden
= null;
3176 this.onWindowResizeTimeout
= null;
3177 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
3178 this.afterWindowResizeHandler
= this.afterWindowResize
.bind( this );
3182 .addClass( 'oo-ui-windowManager' )
3183 .toggleClass( 'oo-ui-windowManager-modal', this.modal
);
3188 OO
.inheritClass( OO
.ui
.WindowManager
, OO
.ui
.Element
);
3189 OO
.mixinClass( OO
.ui
.WindowManager
, OO
.EventEmitter
);
3194 * An 'opening' event is emitted when the window begins to be opened.
3197 * @param {OO.ui.Window} win Window that's being opened
3198 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
3199 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
3200 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
3201 * @param {Object} data Window opening data
3205 * A 'closing' event is emitted when the window begins to be closed.
3208 * @param {OO.ui.Window} win Window that's being closed
3209 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
3210 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
3211 * processes are complete. When the `closing` promise is resolved, the first argument of its value
3212 * is the closing data.
3213 * @param {Object} data Window closing data
3217 * A 'resize' event is emitted when a window is resized.
3220 * @param {OO.ui.Window} win Window that was resized
3223 /* Static Properties */
3226 * Map of the symbolic name of each window size and its CSS properties.
3230 * @property {Object}
3232 OO
.ui
.WindowManager
.static.sizes
= {
3246 // These can be non-numeric because they are never used in calculations
3253 * Symbolic name of the default window size.
3255 * The default size is used if the window's requested size is not recognized.
3259 * @property {string}
3261 OO
.ui
.WindowManager
.static.defaultSize
= 'medium';
3266 * Handle window resize events.
3269 * @param {jQuery.Event} e Window resize event
3271 OO
.ui
.WindowManager
.prototype.onWindowResize = function () {
3272 clearTimeout( this.onWindowResizeTimeout
);
3273 this.onWindowResizeTimeout
= setTimeout( this.afterWindowResizeHandler
, 200 );
3277 * Handle window resize events.
3280 * @param {jQuery.Event} e Window resize event
3282 OO
.ui
.WindowManager
.prototype.afterWindowResize = function () {
3283 if ( this.currentWindow
) {
3284 this.updateWindowSize( this.currentWindow
);
3289 * Check if window is opening.
3291 * @return {boolean} Window is opening
3293 OO
.ui
.WindowManager
.prototype.isOpening = function ( win
) {
3294 return win
=== this.currentWindow
&& !!this.opening
&& this.opening
.state() === 'pending';
3298 * Check if window is closing.
3300 * @return {boolean} Window is closing
3302 OO
.ui
.WindowManager
.prototype.isClosing = function ( win
) {
3303 return win
=== this.currentWindow
&& !!this.closing
&& this.closing
.state() === 'pending';
3307 * Check if window is opened.
3309 * @return {boolean} Window is opened
3311 OO
.ui
.WindowManager
.prototype.isOpened = function ( win
) {
3312 return win
=== this.currentWindow
&& !!this.opened
&& this.opened
.state() === 'pending';
3316 * Check if a window is being managed.
3318 * @param {OO.ui.Window} win Window to check
3319 * @return {boolean} Window is being managed
3321 OO
.ui
.WindowManager
.prototype.hasWindow = function ( win
) {
3324 for ( name
in this.windows
) {
3325 if ( this.windows
[ name
] === win
) {
3334 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
3336 * @param {OO.ui.Window} win Window being opened
3337 * @param {Object} [data] Window opening data
3338 * @return {number} Milliseconds to wait
3340 OO
.ui
.WindowManager
.prototype.getSetupDelay = function () {
3345 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
3347 * @param {OO.ui.Window} win Window being opened
3348 * @param {Object} [data] Window opening data
3349 * @return {number} Milliseconds to wait
3351 OO
.ui
.WindowManager
.prototype.getReadyDelay = function () {
3356 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
3358 * @param {OO.ui.Window} win Window being closed
3359 * @param {Object} [data] Window closing data
3360 * @return {number} Milliseconds to wait
3362 OO
.ui
.WindowManager
.prototype.getHoldDelay = function () {
3367 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
3368 * executing the ‘teardown’ process.
3370 * @param {OO.ui.Window} win Window being closed
3371 * @param {Object} [data] Window closing data
3372 * @return {number} Milliseconds to wait
3374 OO
.ui
.WindowManager
.prototype.getTeardownDelay = function () {
3375 return this.modal
? 250 : 0;
3379 * Get a window by its symbolic name.
3381 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
3382 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
3383 * for more information about using factories.
3384 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3386 * @param {string} name Symbolic name of the window
3387 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
3388 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
3389 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
3391 OO
.ui
.WindowManager
.prototype.getWindow = function ( name
) {
3392 var deferred
= $.Deferred(),
3393 win
= this.windows
[ name
];
3395 if ( !( win
instanceof OO
.ui
.Window
) ) {
3396 if ( this.factory
) {
3397 if ( !this.factory
.lookup( name
) ) {
3398 deferred
.reject( new OO
.ui
.Error(
3399 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
3402 win
= this.factory
.create( name
);
3403 this.addWindows( [ win
] );
3404 deferred
.resolve( win
);
3407 deferred
.reject( new OO
.ui
.Error(
3408 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
3412 deferred
.resolve( win
);
3415 return deferred
.promise();
3419 * Get current window.
3421 * @return {OO.ui.Window|null} Currently opening/opened/closing window
3423 OO
.ui
.WindowManager
.prototype.getCurrentWindow = function () {
3424 return this.currentWindow
;
3430 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
3431 * @param {Object} [data] Window opening data
3432 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3433 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3436 OO
.ui
.WindowManager
.prototype.openWindow = function ( win
, data
) {
3438 opening
= $.Deferred();
3440 // Argument handling
3441 if ( typeof win
=== 'string' ) {
3442 return this.getWindow( win
).then( function ( win
) {
3443 return manager
.openWindow( win
, data
);
3448 if ( !this.hasWindow( win
) ) {
3449 opening
.reject( new OO
.ui
.Error(
3450 'Cannot open window: window is not attached to manager'
3452 } else if ( this.preparingToOpen
|| this.opening
|| this.opened
) {
3453 opening
.reject( new OO
.ui
.Error(
3454 'Cannot open window: another window is opening or open'
3459 if ( opening
.state() !== 'rejected' ) {
3460 // If a window is currently closing, wait for it to complete
3461 this.preparingToOpen
= $.when( this.closing
);
3462 // Ensure handlers get called after preparingToOpen is set
3463 this.preparingToOpen
.done( function () {
3464 if ( manager
.modal
) {
3465 manager
.toggleGlobalEvents( true );
3466 manager
.toggleAriaIsolation( true );
3468 manager
.currentWindow
= win
;
3469 manager
.opening
= opening
;
3470 manager
.preparingToOpen
= null;
3471 manager
.emit( 'opening', win
, opening
, data
);
3472 setTimeout( function () {
3473 win
.setup( data
).then( function () {
3474 manager
.updateWindowSize( win
);
3475 manager
.opening
.notify( { state
: 'setup' } );
3476 setTimeout( function () {
3477 win
.ready( data
).then( function () {
3478 manager
.opening
.notify( { state
: 'ready' } );
3479 manager
.opening
= null;
3480 manager
.opened
= $.Deferred();
3481 opening
.resolve( manager
.opened
.promise(), data
);
3483 }, manager
.getReadyDelay() );
3485 }, manager
.getSetupDelay() );
3489 return opening
.promise();
3495 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3496 * @param {Object} [data] Window closing data
3497 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3498 * See {@link #event-closing 'closing' event} for more information about closing promises.
3499 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3502 OO
.ui
.WindowManager
.prototype.closeWindow = function ( win
, data
) {
3504 closing
= $.Deferred(),
3507 // Argument handling
3508 if ( typeof win
=== 'string' ) {
3509 win
= this.windows
[ win
];
3510 } else if ( !this.hasWindow( win
) ) {
3516 closing
.reject( new OO
.ui
.Error(
3517 'Cannot close window: window is not attached to manager'
3519 } else if ( win
!== this.currentWindow
) {
3520 closing
.reject( new OO
.ui
.Error(
3521 'Cannot close window: window already closed with different data'
3523 } else if ( this.preparingToClose
|| this.closing
) {
3524 closing
.reject( new OO
.ui
.Error(
3525 'Cannot close window: window already closing with different data'
3530 if ( closing
.state() !== 'rejected' ) {
3531 // If the window is currently opening, close it when it's done
3532 this.preparingToClose
= $.when( this.opening
);
3533 // Ensure handlers get called after preparingToClose is set
3534 this.preparingToClose
.done( function () {
3535 manager
.closing
= closing
;
3536 manager
.preparingToClose
= null;
3537 manager
.emit( 'closing', win
, closing
, data
);
3538 opened
= manager
.opened
;
3539 manager
.opened
= null;
3540 opened
.resolve( closing
.promise(), data
);
3541 setTimeout( function () {
3542 win
.hold( data
).then( function () {
3543 closing
.notify( { state
: 'hold' } );
3544 setTimeout( function () {
3545 win
.teardown( data
).then( function () {
3546 closing
.notify( { state
: 'teardown' } );
3547 if ( manager
.modal
) {
3548 manager
.toggleGlobalEvents( false );
3549 manager
.toggleAriaIsolation( false );
3551 manager
.closing
= null;
3552 manager
.currentWindow
= null;
3553 closing
.resolve( data
);
3555 }, manager
.getTeardownDelay() );
3557 }, manager
.getHoldDelay() );
3561 return closing
.promise();
3565 * Add windows to the window manager.
3567 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3568 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3569 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3571 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3572 * by reference, symbolic name, or explicitly defined symbolic names.
3573 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3574 * explicit nor a statically configured symbolic name.
3576 OO
.ui
.WindowManager
.prototype.addWindows = function ( windows
) {
3577 var i
, len
, win
, name
, list
;
3579 if ( Array
.isArray( windows
) ) {
3580 // Convert to map of windows by looking up symbolic names from static configuration
3582 for ( i
= 0, len
= windows
.length
; i
< len
; i
++ ) {
3583 name
= windows
[ i
].constructor.static.name
;
3584 if ( typeof name
!== 'string' ) {
3585 throw new Error( 'Cannot add window' );
3587 list
[ name
] = windows
[ i
];
3589 } else if ( OO
.isPlainObject( windows
) ) {
3594 for ( name
in list
) {
3596 this.windows
[ name
] = win
.toggle( false );
3597 this.$element
.append( win
.$element
);
3598 win
.setManager( this );
3603 * Remove the specified windows from the windows manager.
3605 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3606 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3607 * longer listens to events, use the #destroy method.
3609 * @param {string[]} names Symbolic names of windows to remove
3610 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3611 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3613 OO
.ui
.WindowManager
.prototype.removeWindows = function ( names
) {
3614 var i
, len
, win
, name
, cleanupWindow
,
3617 cleanup = function ( name
, win
) {
3618 delete manager
.windows
[ name
];
3619 win
.$element
.detach();
3622 for ( i
= 0, len
= names
.length
; i
< len
; i
++ ) {
3624 win
= this.windows
[ name
];
3626 throw new Error( 'Cannot remove window' );
3628 cleanupWindow
= cleanup
.bind( null, name
, win
);
3629 promises
.push( this.closeWindow( name
).then( cleanupWindow
, cleanupWindow
) );
3632 return $.when
.apply( $, promises
);
3636 * Remove all windows from the window manager.
3638 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3639 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3640 * To remove just a subset of windows, use the #removeWindows method.
3642 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3644 OO
.ui
.WindowManager
.prototype.clearWindows = function () {
3645 return this.removeWindows( Object
.keys( this.windows
) );
3649 * Set dialog size. In general, this method should not be called directly.
3651 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3655 OO
.ui
.WindowManager
.prototype.updateWindowSize = function ( win
) {
3658 // Bypass for non-current, and thus invisible, windows
3659 if ( win
!== this.currentWindow
) {
3663 isFullscreen
= win
.getSize() === 'full';
3665 this.$element
.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen
);
3666 this.$element
.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen
);
3667 win
.setDimensions( win
.getSizeProperties() );
3669 this.emit( 'resize', win
);
3675 * Bind or unbind global events for scrolling.
3678 * @param {boolean} [on] Bind global events
3681 OO
.ui
.WindowManager
.prototype.toggleGlobalEvents = function ( on
) {
3682 var scrollWidth
, bodyMargin
,
3683 $body
= $( this.getElementDocument().body
),
3684 // We could have multiple window managers open so only modify
3685 // the body css at the bottom of the stack
3686 stackDepth
= $body
.data( 'windowManagerGlobalEvents' ) || 0 ;
3688 on
= on
=== undefined ? !!this.globalEvents
: !!on
;
3691 if ( !this.globalEvents
) {
3692 $( this.getElementWindow() ).on( {
3693 // Start listening for top-level window dimension changes
3694 'orientationchange resize': this.onWindowResizeHandler
3696 if ( stackDepth
=== 0 ) {
3697 scrollWidth
= window
.innerWidth
- document
.documentElement
.clientWidth
;
3698 bodyMargin
= parseFloat( $body
.css( 'margin-right' ) ) || 0;
3701 'margin-right': bodyMargin
+ scrollWidth
3705 this.globalEvents
= true;
3707 } else if ( this.globalEvents
) {
3708 $( this.getElementWindow() ).off( {
3709 // Stop listening for top-level window dimension changes
3710 'orientationchange resize': this.onWindowResizeHandler
3713 if ( stackDepth
=== 0 ) {
3719 this.globalEvents
= false;
3721 $body
.data( 'windowManagerGlobalEvents', stackDepth
);
3727 * Toggle screen reader visibility of content other than the window manager.
3730 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3733 OO
.ui
.WindowManager
.prototype.toggleAriaIsolation = function ( isolate
) {
3734 isolate
= isolate
=== undefined ? !this.$ariaHidden
: !!isolate
;
3737 if ( !this.$ariaHidden
) {
3738 // Hide everything other than the window manager from screen readers
3739 this.$ariaHidden
= $( 'body' )
3741 .not( this.$element
.parentsUntil( 'body' ).last() )
3742 .attr( 'aria-hidden', '' );
3744 } else if ( this.$ariaHidden
) {
3745 // Restore screen reader visibility
3746 this.$ariaHidden
.removeAttr( 'aria-hidden' );
3747 this.$ariaHidden
= null;
3754 * Destroy the window manager.
3756 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3757 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3760 OO
.ui
.WindowManager
.prototype.destroy = function () {
3761 this.toggleGlobalEvents( false );
3762 this.toggleAriaIsolation( false );
3763 this.clearWindows();
3764 this.$element
.remove();
3768 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3769 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3770 * appearance and functionality of the error interface.
3772 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3773 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3774 * that initiated the failed process will be disabled.
3776 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3779 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3781 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3786 * @param {string|jQuery} message Description of error
3787 * @param {Object} [config] Configuration options
3788 * @cfg {boolean} [recoverable=true] Error is recoverable.
3789 * By default, errors are recoverable, and users can try the process again.
3790 * @cfg {boolean} [warning=false] Error is a warning.
3791 * If the error is a warning, the error interface will include a
3792 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3793 * is not triggered a second time if the user chooses to continue.
3795 OO
.ui
.Error
= function OoUiError( message
, config
) {
3796 // Allow passing positional parameters inside the config object
3797 if ( OO
.isPlainObject( message
) && config
=== undefined ) {
3799 message
= config
.message
;
3802 // Configuration initialization
3803 config
= config
|| {};
3806 this.message
= message
instanceof jQuery
? message
: String( message
);
3807 this.recoverable
= config
.recoverable
=== undefined || !!config
.recoverable
;
3808 this.warning
= !!config
.warning
;
3813 OO
.initClass( OO
.ui
.Error
);
3818 * Check if the error is recoverable.
3820 * If the error is recoverable, users are able to try the process again.
3822 * @return {boolean} Error is recoverable
3824 OO
.ui
.Error
.prototype.isRecoverable = function () {
3825 return this.recoverable
;
3829 * Check if the error is a warning.
3831 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3833 * @return {boolean} Error is warning
3835 OO
.ui
.Error
.prototype.isWarning = function () {
3836 return this.warning
;
3840 * Get error message as DOM nodes.
3842 * @return {jQuery} Error message in DOM nodes
3844 OO
.ui
.Error
.prototype.getMessage = function () {
3845 return this.message
instanceof jQuery
?
3846 this.message
.clone() :
3847 $( '<div>' ).text( this.message
).contents();
3851 * Get the error message text.
3853 * @return {string} Error message
3855 OO
.ui
.Error
.prototype.getMessageText = function () {
3856 return this.message
instanceof jQuery
? this.message
.text() : this.message
;
3860 * Wraps an HTML snippet for use with configuration values which default
3861 * to strings. This bypasses the default html-escaping done to string
3867 * @param {string} [content] HTML content
3869 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
3871 this.content
= content
;
3876 OO
.initClass( OO
.ui
.HtmlSnippet
);
3883 * @return {string} Unchanged HTML snippet.
3885 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
3886 return this.content
;
3890 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3893 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3894 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3895 * or stop if the promise is rejected.
3896 * - **function**: the process will execute the function. The process will stop if the function returns
3897 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3898 * will wait for that number of milliseconds before proceeding.
3900 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3901 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3902 * its remaining steps will not be performed.
3907 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3908 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3909 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3910 * a number or promise.
3911 * @return {Object} Step object, with `callback` and `context` properties
3913 OO
.ui
.Process = function ( step
, context
) {
3918 if ( step
!== undefined ) {
3919 this.next( step
, context
);
3925 OO
.initClass( OO
.ui
.Process
);
3930 * Start the process.
3932 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
3933 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
3934 * and any remaining steps are not performed.
3936 OO
.ui
.Process
.prototype.execute = function () {
3937 var i
, len
, promise
;
3940 * Continue execution.
3943 * @param {Array} step A function and the context it should be called in
3944 * @return {Function} Function that continues the process
3946 function proceed( step
) {
3947 return function () {
3948 // Execute step in the correct context
3950 result
= step
.callback
.call( step
.context
);
3952 if ( result
=== false ) {
3953 // Use rejected promise for boolean false results
3954 return $.Deferred().reject( [] ).promise();
3956 if ( typeof result
=== 'number' ) {
3958 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3960 // Use a delayed promise for numbers, expecting them to be in milliseconds
3961 deferred
= $.Deferred();
3962 setTimeout( deferred
.resolve
, result
);
3963 return deferred
.promise();
3965 if ( result
instanceof OO
.ui
.Error
) {
3966 // Use rejected promise for error
3967 return $.Deferred().reject( [ result
] ).promise();
3969 if ( Array
.isArray( result
) && result
.length
&& result
[ 0 ] instanceof OO
.ui
.Error
) {
3970 // Use rejected promise for list of errors
3971 return $.Deferred().reject( result
).promise();
3973 // Duck-type the object to see if it can produce a promise
3974 if ( result
&& $.isFunction( result
.promise
) ) {
3975 // Use a promise generated from the result
3976 return result
.promise();
3978 // Use resolved promise for other results
3979 return $.Deferred().resolve().promise();
3983 if ( this.steps
.length
) {
3984 // Generate a chain reaction of promises
3985 promise
= proceed( this.steps
[ 0 ] )();
3986 for ( i
= 1, len
= this.steps
.length
; i
< len
; i
++ ) {
3987 promise
= promise
.then( proceed( this.steps
[ i
] ) );
3990 promise
= $.Deferred().resolve().promise();
3997 * Create a process step.
4000 * @param {number|jQuery.Promise|Function} step
4002 * - Number of milliseconds to wait before proceeding
4003 * - Promise that must be resolved before proceeding
4004 * - Function to execute
4005 * - If the function returns a boolean false the process will stop
4006 * - If the function returns a promise, the process will continue to the next
4007 * step when the promise is resolved or stop if the promise is rejected
4008 * - If the function returns a number, the process will wait for that number of
4009 * milliseconds before proceeding
4010 * @param {Object} [context=null] Execution context of the function. The context is
4011 * ignored if the step is a number or promise.
4012 * @return {Object} Step object, with `callback` and `context` properties
4014 OO
.ui
.Process
.prototype.createStep = function ( step
, context
) {
4015 if ( typeof step
=== 'number' || $.isFunction( step
.promise
) ) {
4017 callback: function () {
4023 if ( $.isFunction( step
) ) {
4029 throw new Error( 'Cannot create process step: number, promise or function expected' );
4033 * Add step to the beginning of the process.
4035 * @inheritdoc #createStep
4036 * @return {OO.ui.Process} this
4039 OO
.ui
.Process
.prototype.first = function ( step
, context
) {
4040 this.steps
.unshift( this.createStep( step
, context
) );
4045 * Add step to the end of the process.
4047 * @inheritdoc #createStep
4048 * @return {OO.ui.Process} this
4051 OO
.ui
.Process
.prototype.next = function ( step
, context
) {
4052 this.steps
.push( this.createStep( step
, context
) );
4057 * A ToolFactory creates tools on demand. All tools ({@link OO.ui.Tool Tools}, {@link OO.ui.PopupTool PopupTools},
4058 * and {@link OO.ui.ToolGroupTool ToolGroupTools}) must be registered with a tool factory. Tools are
4059 * registered by their symbolic name. See {@link OO.ui.Toolbar toolbars} for an example.
4061 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4063 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4066 * @extends OO.Factory
4069 OO
.ui
.ToolFactory
= function OoUiToolFactory() {
4070 // Parent constructor
4071 OO
.ui
.ToolFactory
.parent
.call( this );
4076 OO
.inheritClass( OO
.ui
.ToolFactory
, OO
.Factory
);
4081 * Get tools from the factory
4083 * @param {Array} include Included tools
4084 * @param {Array} exclude Excluded tools
4085 * @param {Array} promote Promoted tools
4086 * @param {Array} demote Demoted tools
4087 * @return {string[]} List of tools
4089 OO
.ui
.ToolFactory
.prototype.getTools = function ( include
, exclude
, promote
, demote
) {
4090 var i
, len
, included
, promoted
, demoted
,
4094 // Collect included and not excluded tools
4095 included
= OO
.simpleArrayDifference( this.extract( include
), this.extract( exclude
) );
4098 promoted
= this.extract( promote
, used
);
4099 demoted
= this.extract( demote
, used
);
4102 for ( i
= 0, len
= included
.length
; i
< len
; i
++ ) {
4103 if ( !used
[ included
[ i
] ] ) {
4104 auto
.push( included
[ i
] );
4108 return promoted
.concat( auto
).concat( demoted
);
4112 * Get a flat list of names from a list of names or groups.
4114 * Tools can be specified in the following ways:
4116 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
4117 * - All tools in a group: `{ group: 'group-name' }`
4118 * - All tools: `'*'`
4121 * @param {Array|string} collection List of tools
4122 * @param {Object} [used] Object with names that should be skipped as properties; extracted
4123 * names will be added as properties
4124 * @return {string[]} List of extracted names
4126 OO
.ui
.ToolFactory
.prototype.extract = function ( collection
, used
) {
4127 var i
, len
, item
, name
, tool
,
4130 if ( collection
=== '*' ) {
4131 for ( name
in this.registry
) {
4132 tool
= this.registry
[ name
];
4134 // Only add tools by group name when auto-add is enabled
4135 tool
.static.autoAddToCatchall
&&
4136 // Exclude already used tools
4137 ( !used
|| !used
[ name
] )
4141 used
[ name
] = true;
4145 } else if ( Array
.isArray( collection
) ) {
4146 for ( i
= 0, len
= collection
.length
; i
< len
; i
++ ) {
4147 item
= collection
[ i
];
4148 // Allow plain strings as shorthand for named tools
4149 if ( typeof item
=== 'string' ) {
4150 item
= { name
: item
};
4152 if ( OO
.isPlainObject( item
) ) {
4154 for ( name
in this.registry
) {
4155 tool
= this.registry
[ name
];
4157 // Include tools with matching group
4158 tool
.static.group
=== item
.group
&&
4159 // Only add tools by group name when auto-add is enabled
4160 tool
.static.autoAddToGroup
&&
4161 // Exclude already used tools
4162 ( !used
|| !used
[ name
] )
4166 used
[ name
] = true;
4170 // Include tools with matching name and exclude already used tools
4171 } else if ( item
.name
&& ( !used
|| !used
[ item
.name
] ) ) {
4172 names
.push( item
.name
);
4174 used
[ item
.name
] = true;
4184 * ToolGroupFactories create {@link OO.ui.ToolGroup toolgroups} on demand. The toolgroup classes must
4185 * specify a symbolic name and be registered with the factory. The following classes are registered by
4188 * - {@link OO.ui.BarToolGroup BarToolGroups} (‘bar’)
4189 * - {@link OO.ui.MenuToolGroup MenuToolGroups} (‘menu’)
4190 * - {@link OO.ui.ListToolGroup ListToolGroups} (‘list’)
4192 * See {@link OO.ui.Toolbar toolbars} for an example.
4194 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4196 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4198 * @extends OO.Factory
4201 OO
.ui
.ToolGroupFactory
= function OoUiToolGroupFactory() {
4202 var i
, l
, defaultClasses
;
4203 // Parent constructor
4204 OO
.Factory
.call( this );
4206 defaultClasses
= this.constructor.static.getDefaultClasses();
4208 // Register default toolgroups
4209 for ( i
= 0, l
= defaultClasses
.length
; i
< l
; i
++ ) {
4210 this.register( defaultClasses
[ i
] );
4216 OO
.inheritClass( OO
.ui
.ToolGroupFactory
, OO
.Factory
);
4218 /* Static Methods */
4221 * Get a default set of classes to be registered on construction.
4223 * @return {Function[]} Default classes
4225 OO
.ui
.ToolGroupFactory
.static.getDefaultClasses = function () {
4228 OO
.ui
.ListToolGroup
,
4240 * @param {Object} [config] Configuration options
4242 OO
.ui
.Theme
= function OoUiTheme( config
) {
4243 // Configuration initialization
4244 config
= config
|| {};
4249 OO
.initClass( OO
.ui
.Theme
);
4254 * Get a list of classes to be applied to a widget.
4256 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
4257 * otherwise state transitions will not work properly.
4259 * @param {OO.ui.Element} element Element for which to get classes
4260 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4262 OO
.ui
.Theme
.prototype.getElementClasses = function () {
4263 return { on
: [], off
: [] };
4267 * Update CSS classes provided by the theme.
4269 * For elements with theme logic hooks, this should be called any time there's a state change.
4271 * @param {OO.ui.Element} element Element for which to update classes
4272 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4274 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
4275 var $elements
= $( [] ),
4276 classes
= this.getElementClasses( element
);
4278 if ( element
.$icon
) {
4279 $elements
= $elements
.add( element
.$icon
);
4281 if ( element
.$indicator
) {
4282 $elements
= $elements
.add( element
.$indicator
);
4286 .removeClass( classes
.off
.join( ' ' ) )
4287 .addClass( classes
.on
.join( ' ' ) );
4291 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
4292 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
4293 * order in which users will navigate through the focusable elements via the "tab" key.
4296 * // TabIndexedElement is mixed into the ButtonWidget class
4297 * // to provide a tabIndex property.
4298 * var button1 = new OO.ui.ButtonWidget( {
4302 * var button2 = new OO.ui.ButtonWidget( {
4306 * var button3 = new OO.ui.ButtonWidget( {
4310 * var button4 = new OO.ui.ButtonWidget( {
4314 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
4320 * @param {Object} [config] Configuration options
4321 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
4322 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
4323 * functionality will be applied to it instead.
4324 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
4325 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
4326 * to remove the element from the tab-navigation flow.
4328 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
4329 // Configuration initialization
4330 config
= $.extend( { tabIndex
: 0 }, config
);
4333 this.$tabIndexed
= null;
4334 this.tabIndex
= null;
4337 this.connect( this, { disable
: 'onTabIndexedElementDisable' } );
4340 this.setTabIndex( config
.tabIndex
);
4341 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
4346 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
4351 * Set the element that should use the tabindex functionality.
4353 * This method is used to retarget a tabindex mixin so that its functionality applies
4354 * to the specified element. If an element is currently using the functionality, the mixin’s
4355 * effect on that element is removed before the new element is set up.
4357 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
4360 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
4361 var tabIndex
= this.tabIndex
;
4362 // Remove attributes from old $tabIndexed
4363 this.setTabIndex( null );
4364 // Force update of new $tabIndexed
4365 this.$tabIndexed
= $tabIndexed
;
4366 this.tabIndex
= tabIndex
;
4367 return this.updateTabIndex();
4371 * Set the value of the tabindex.
4373 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
4376 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
4377 tabIndex
= typeof tabIndex
=== 'number' ? tabIndex
: null;
4379 if ( this.tabIndex
!== tabIndex
) {
4380 this.tabIndex
= tabIndex
;
4381 this.updateTabIndex();
4388 * Update the `tabindex` attribute, in case of changes to tab index or
4394 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
4395 if ( this.$tabIndexed
) {
4396 if ( this.tabIndex
!== null ) {
4397 // Do not index over disabled elements
4398 this.$tabIndexed
.attr( {
4399 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
4400 // Support: ChromeVox and NVDA
4401 // These do not seem to inherit aria-disabled from parent elements
4402 'aria-disabled': this.isDisabled().toString()
4405 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
4412 * Handle disable events.
4415 * @param {boolean} disabled Element is disabled
4417 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
4418 this.updateTabIndex();
4422 * Get the value of the tabindex.
4424 * @return {number|null} Tabindex value
4426 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
4427 return this.tabIndex
;
4431 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
4432 * interface element that can be configured with access keys for accessibility.
4433 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
4435 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
4440 * @param {Object} [config] Configuration options
4441 * @cfg {jQuery} [$button] The button element created by the class.
4442 * If this configuration is omitted, the button element will use a generated `<a>`.
4443 * @cfg {boolean} [framed=true] Render the button with a frame
4445 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
4446 // Configuration initialization
4447 config
= config
|| {};
4450 this.$button
= null;
4452 this.active
= false;
4453 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
4454 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
4455 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
4456 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
4457 this.onClickHandler
= this.onClick
.bind( this );
4458 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
4461 this.$element
.addClass( 'oo-ui-buttonElement' );
4462 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
4463 this.setButtonElement( config
.$button
|| $( '<a>' ) );
4468 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
4470 /* Static Properties */
4473 * Cancel mouse down events.
4475 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4476 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4477 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4482 * @property {boolean}
4484 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
4489 * A 'click' event is emitted when the button element is clicked.
4497 * Set the button element.
4499 * This method is used to retarget a button mixin so that its functionality applies to
4500 * the specified button element instead of the one created by the class. If a button element
4501 * is already set, the method will remove the mixin’s effect on that element.
4503 * @param {jQuery} $button Element to use as button
4505 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
4506 if ( this.$button
) {
4508 .removeClass( 'oo-ui-buttonElement-button' )
4509 .removeAttr( 'role accesskey' )
4511 mousedown
: this.onMouseDownHandler
,
4512 keydown
: this.onKeyDownHandler
,
4513 click
: this.onClickHandler
,
4514 keypress
: this.onKeyPressHandler
4518 this.$button
= $button
4519 .addClass( 'oo-ui-buttonElement-button' )
4520 .attr( { role
: 'button' } )
4522 mousedown
: this.onMouseDownHandler
,
4523 keydown
: this.onKeyDownHandler
,
4524 click
: this.onClickHandler
,
4525 keypress
: this.onKeyPressHandler
4530 * Handles mouse down events.
4533 * @param {jQuery.Event} e Mouse down event
4535 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
4536 if ( this.isDisabled() || e
.which
!== 1 ) {
4539 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4540 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4541 // reliably remove the pressed class
4542 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler
);
4543 // Prevent change of focus unless specifically configured otherwise
4544 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
4550 * Handles mouse up events.
4553 * @param {jQuery.Event} e Mouse up event
4555 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp = function ( e
) {
4556 if ( this.isDisabled() || e
.which
!== 1 ) {
4559 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4560 // Stop listening for mouseup, since we only needed this once
4561 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler
);
4565 * Handles mouse click events.
4568 * @param {jQuery.Event} e Mouse click event
4571 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
4572 if ( !this.isDisabled() && e
.which
=== 1 ) {
4573 if ( this.emit( 'click' ) ) {
4580 * Handles key down events.
4583 * @param {jQuery.Event} e Key down event
4585 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
4586 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4589 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4590 // Run the keyup handler no matter where the key is when the button is let go, so we can
4591 // reliably remove the pressed class
4592 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler
);
4596 * Handles key up events.
4599 * @param {jQuery.Event} e Key up event
4601 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyUp = function ( e
) {
4602 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4605 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4606 // Stop listening for keyup, since we only needed this once
4607 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler
);
4611 * Handles key press events.
4614 * @param {jQuery.Event} e Key press event
4617 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
4618 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
4619 if ( this.emit( 'click' ) ) {
4626 * Check if button has a frame.
4628 * @return {boolean} Button is framed
4630 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
4635 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4637 * @param {boolean} [framed] Make button framed, omit to toggle
4640 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
4641 framed
= framed
=== undefined ? !this.framed
: !!framed
;
4642 if ( framed
!== this.framed
) {
4643 this.framed
= framed
;
4645 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
4646 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
4647 this.updateThemeClasses();
4654 * Set the button's active state.
4656 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4657 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4658 * for other button types.
4660 * @param {boolean} value Make button active
4663 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
4664 this.active
= !!value
;
4665 this.$element
.toggleClass( 'oo-ui-buttonElement-active', this.active
);
4670 * Check if the button is active
4672 * @return {boolean} The button is active
4674 OO
.ui
.mixin
.ButtonElement
.prototype.isActive = function () {
4679 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4680 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4681 * items from the group is done through the interface the class provides.
4682 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4684 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4690 * @param {Object} [config] Configuration options
4691 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4692 * is omitted, the group element will use a generated `<div>`.
4694 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
4695 // Configuration initialization
4696 config
= config
|| {};
4701 this.aggregateItemEvents
= {};
4704 this.setGroupElement( config
.$group
|| $( '<div>' ) );
4710 * Set the group element.
4712 * If an element is already set, items will be moved to the new element.
4714 * @param {jQuery} $group Element to use as group
4716 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
4719 this.$group
= $group
;
4720 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4721 this.$group
.append( this.items
[ i
].$element
);
4726 * Check if a group contains no items.
4728 * @return {boolean} Group is empty
4730 OO
.ui
.mixin
.GroupElement
.prototype.isEmpty = function () {
4731 return !this.items
.length
;
4735 * Get all items in the group.
4737 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4738 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4741 * @return {OO.ui.Element[]} An array of items.
4743 OO
.ui
.mixin
.GroupElement
.prototype.getItems = function () {
4744 return this.items
.slice( 0 );
4748 * Get an item by its data.
4750 * Only the first item with matching data will be returned. To return all matching items,
4751 * use the #getItemsFromData method.
4753 * @param {Object} data Item data to search for
4754 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4756 OO
.ui
.mixin
.GroupElement
.prototype.getItemFromData = function ( data
) {
4758 hash
= OO
.getHash( data
);
4760 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4761 item
= this.items
[ i
];
4762 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4771 * Get items by their data.
4773 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4775 * @param {Object} data Item data to search for
4776 * @return {OO.ui.Element[]} Items with equivalent data
4778 OO
.ui
.mixin
.GroupElement
.prototype.getItemsFromData = function ( data
) {
4780 hash
= OO
.getHash( data
),
4783 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4784 item
= this.items
[ i
];
4785 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4794 * Aggregate the events emitted by the group.
4796 * When events are aggregated, the group will listen to all contained items for the event,
4797 * and then emit the event under a new name. The new event will contain an additional leading
4798 * parameter containing the item that emitted the original event. Other arguments emitted from
4799 * the original event are passed through.
4801 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4802 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4803 * A `null` value will remove aggregated events.
4805 * @throws {Error} An error is thrown if aggregation already exists.
4807 OO
.ui
.mixin
.GroupElement
.prototype.aggregate = function ( events
) {
4808 var i
, len
, item
, add
, remove
, itemEvent
, groupEvent
;
4810 for ( itemEvent
in events
) {
4811 groupEvent
= events
[ itemEvent
];
4813 // Remove existing aggregated event
4814 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4815 // Don't allow duplicate aggregations
4817 throw new Error( 'Duplicate item event aggregation for ' + itemEvent
);
4819 // Remove event aggregation from existing items
4820 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4821 item
= this.items
[ i
];
4822 if ( item
.connect
&& item
.disconnect
) {
4824 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4825 item
.disconnect( this, remove
);
4828 // Prevent future items from aggregating event
4829 delete this.aggregateItemEvents
[ itemEvent
];
4832 // Add new aggregate event
4834 // Make future items aggregate event
4835 this.aggregateItemEvents
[ itemEvent
] = groupEvent
;
4836 // Add event aggregation to existing items
4837 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4838 item
= this.items
[ i
];
4839 if ( item
.connect
&& item
.disconnect
) {
4841 add
[ itemEvent
] = [ 'emit', groupEvent
, item
];
4842 item
.connect( this, add
);
4850 * Add items to the group.
4852 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4853 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4855 * @param {OO.ui.Element[]} items An array of items to add to the group
4856 * @param {number} [index] Index of the insertion point
4859 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
4860 var i
, len
, item
, event
, events
, currentIndex
,
4863 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4866 // Check if item exists then remove it first, effectively "moving" it
4867 currentIndex
= this.items
.indexOf( item
);
4868 if ( currentIndex
>= 0 ) {
4869 this.removeItems( [ item
] );
4870 // Adjust index to compensate for removal
4871 if ( currentIndex
< index
) {
4876 if ( item
.connect
&& item
.disconnect
&& !$.isEmptyObject( this.aggregateItemEvents
) ) {
4878 for ( event
in this.aggregateItemEvents
) {
4879 events
[ event
] = [ 'emit', this.aggregateItemEvents
[ event
], item
];
4881 item
.connect( this, events
);
4883 item
.setElementGroup( this );
4884 itemElements
.push( item
.$element
.get( 0 ) );
4887 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
4888 this.$group
.append( itemElements
);
4889 this.items
.push
.apply( this.items
, items
);
4890 } else if ( index
=== 0 ) {
4891 this.$group
.prepend( itemElements
);
4892 this.items
.unshift
.apply( this.items
, items
);
4894 this.items
[ index
].$element
.before( itemElements
);
4895 this.items
.splice
.apply( this.items
, [ index
, 0 ].concat( items
) );
4902 * Remove the specified items from a group.
4904 * Removed items are detached (not removed) from the DOM so that they may be reused.
4905 * To remove all items from a group, you may wish to use the #clearItems method instead.
4907 * @param {OO.ui.Element[]} items An array of items to remove
4910 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
4911 var i
, len
, item
, index
, remove
, itemEvent
;
4913 // Remove specific items
4914 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4916 index
= this.items
.indexOf( item
);
4917 if ( index
!== -1 ) {
4919 item
.connect
&& item
.disconnect
&&
4920 !$.isEmptyObject( this.aggregateItemEvents
)
4923 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4924 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4926 item
.disconnect( this, remove
);
4928 item
.setElementGroup( null );
4929 this.items
.splice( index
, 1 );
4930 item
.$element
.detach();
4938 * Clear all items from the group.
4940 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4941 * To remove only a subset of items from a group, use the #removeItems method.
4945 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
4946 var i
, len
, item
, remove
, itemEvent
;
4949 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4950 item
= this.items
[ i
];
4952 item
.connect
&& item
.disconnect
&&
4953 !$.isEmptyObject( this.aggregateItemEvents
)
4956 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4957 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4959 item
.disconnect( this, remove
);
4961 item
.setElementGroup( null );
4962 item
.$element
.detach();
4970 * DraggableElement is a mixin class used to create elements that can be clicked
4971 * and dragged by a mouse to a new position within a group. This class must be used
4972 * in conjunction with OO.ui.mixin.DraggableGroupElement, which provides a container for
4973 * the draggable elements.
4980 OO
.ui
.mixin
.DraggableElement
= function OoUiMixinDraggableElement() {
4984 // Initialize and events
4986 .attr( 'draggable', true )
4987 .addClass( 'oo-ui-draggableElement' )
4989 dragstart
: this.onDragStart
.bind( this ),
4990 dragover
: this.onDragOver
.bind( this ),
4991 dragend
: this.onDragEnd
.bind( this ),
4992 drop
: this.onDrop
.bind( this )
4996 OO
.initClass( OO
.ui
.mixin
.DraggableElement
);
5003 * A dragstart event is emitted when the user clicks and begins dragging an item.
5004 * @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse.
5009 * A dragend event is emitted when the user drags an item and releases the mouse,
5010 * thus terminating the drag operation.
5015 * A drop event is emitted when the user drags an item and then releases the mouse button
5016 * over a valid target.
5019 /* Static Properties */
5022 * @inheritdoc OO.ui.mixin.ButtonElement
5024 OO
.ui
.mixin
.DraggableElement
.static.cancelButtonMouseDownEvents
= false;
5029 * Respond to dragstart event.
5032 * @param {jQuery.Event} event jQuery event
5035 OO
.ui
.mixin
.DraggableElement
.prototype.onDragStart = function ( e
) {
5036 var dataTransfer
= e
.originalEvent
.dataTransfer
;
5037 // Define drop effect
5038 dataTransfer
.dropEffect
= 'none';
5039 dataTransfer
.effectAllowed
= 'move';
5041 // We must set up a dataTransfer data property or Firefox seems to
5042 // ignore the fact the element is draggable.
5044 dataTransfer
.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
5046 // The above is only for Firefox. Move on if it fails.
5048 // Add dragging class
5049 this.$element
.addClass( 'oo-ui-draggableElement-dragging' );
5051 this.emit( 'dragstart', this );
5056 * Respond to dragend event.
5061 OO
.ui
.mixin
.DraggableElement
.prototype.onDragEnd = function () {
5062 this.$element
.removeClass( 'oo-ui-draggableElement-dragging' );
5063 this.emit( 'dragend' );
5067 * Handle drop event.
5070 * @param {jQuery.Event} event jQuery event
5073 OO
.ui
.mixin
.DraggableElement
.prototype.onDrop = function ( e
) {
5075 this.emit( 'drop', e
);
5079 * In order for drag/drop to work, the dragover event must
5080 * return false and stop propogation.
5084 OO
.ui
.mixin
.DraggableElement
.prototype.onDragOver = function ( e
) {
5090 * Store it in the DOM so we can access from the widget drag event
5093 * @param {number} Item index
5095 OO
.ui
.mixin
.DraggableElement
.prototype.setIndex = function ( index
) {
5096 if ( this.index
!== index
) {
5098 this.$element
.data( 'index', index
);
5106 * @return {number} Item index
5108 OO
.ui
.mixin
.DraggableElement
.prototype.getIndex = function () {
5113 * DraggableGroupElement is a mixin class used to create a group element to
5114 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
5115 * The class is used with OO.ui.mixin.DraggableElement.
5119 * @mixins OO.ui.mixin.GroupElement
5122 * @param {Object} [config] Configuration options
5123 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
5124 * should match the layout of the items. Items displayed in a single row
5125 * or in several rows should use horizontal orientation. The vertical orientation should only be
5126 * used when the items are displayed in a single column. Defaults to 'vertical'
5128 OO
.ui
.mixin
.DraggableGroupElement
= function OoUiMixinDraggableGroupElement( config
) {
5129 // Configuration initialization
5130 config
= config
|| {};
5132 // Parent constructor
5133 OO
.ui
.mixin
.GroupElement
.call( this, config
);
5136 this.orientation
= config
.orientation
|| 'vertical';
5137 this.dragItem
= null;
5138 this.itemDragOver
= null;
5140 this.sideInsertion
= '';
5144 dragstart
: 'itemDragStart',
5145 dragend
: 'itemDragEnd',
5148 this.connect( this, {
5149 itemDragStart
: 'onItemDragStart',
5150 itemDrop
: 'onItemDrop',
5151 itemDragEnd
: 'onItemDragEnd'
5154 dragover
: this.onDragOver
.bind( this ),
5155 dragleave
: this.onDragLeave
.bind( this )
5159 if ( Array
.isArray( config
.items
) ) {
5160 this.addItems( config
.items
);
5162 this.$placeholder
= $( '<div>' )
5163 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
5165 .addClass( 'oo-ui-draggableGroupElement' )
5166 .append( this.$status
)
5167 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation
=== 'horizontal' )
5168 .prepend( this.$placeholder
);
5172 OO
.mixinClass( OO
.ui
.mixin
.DraggableGroupElement
, OO
.ui
.mixin
.GroupElement
);
5177 * A 'reorder' event is emitted when the order of items in the group changes.
5180 * @param {OO.ui.mixin.DraggableElement} item Reordered item
5181 * @param {number} [newIndex] New index for the item
5187 * Respond to item drag start event
5190 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5192 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDragStart = function ( item
) {
5195 // Map the index of each object
5196 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5197 this.items
[ i
].setIndex( i
);
5200 if ( this.orientation
=== 'horizontal' ) {
5201 // Set the height of the indicator
5202 this.$placeholder
.css( {
5203 height
: item
.$element
.outerHeight(),
5207 // Set the width of the indicator
5208 this.$placeholder
.css( {
5210 width
: item
.$element
.outerWidth()
5213 this.setDragItem( item
);
5217 * Respond to item drag end event
5221 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDragEnd = function () {
5222 this.unsetDragItem();
5227 * Handle drop event and switch the order of the items accordingly
5230 * @param {OO.ui.mixin.DraggableElement} item Dropped item
5233 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDrop = function ( item
) {
5234 var toIndex
= item
.getIndex();
5235 // Check if the dropped item is from the current group
5236 // TODO: Figure out a way to configure a list of legally droppable
5237 // elements even if they are not yet in the list
5238 if ( this.getDragItem() ) {
5239 // If the insertion point is 'after', the insertion index
5240 // is shifted to the right (or to the left in RTL, hence 'after')
5241 if ( this.sideInsertion
=== 'after' ) {
5244 // Emit change event
5245 this.emit( 'reorder', this.getDragItem(), toIndex
);
5247 this.unsetDragItem();
5248 // Return false to prevent propogation
5253 * Handle dragleave event.
5257 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onDragLeave = function () {
5258 // This means the item was dragged outside the widget
5261 .addClass( 'oo-ui-element-hidden' );
5265 * Respond to dragover event
5268 * @param {jQuery.Event} event Event details
5270 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onDragOver = function ( e
) {
5271 var dragOverObj
, $optionWidget
, itemOffset
, itemMidpoint
, itemBoundingRect
,
5272 itemSize
, cssOutput
, dragPosition
, itemIndex
, itemPosition
,
5273 clientX
= e
.originalEvent
.clientX
,
5274 clientY
= e
.originalEvent
.clientY
;
5276 // Get the OptionWidget item we are dragging over
5277 dragOverObj
= this.getElementDocument().elementFromPoint( clientX
, clientY
);
5278 $optionWidget
= $( dragOverObj
).closest( '.oo-ui-draggableElement' );
5279 if ( $optionWidget
[ 0 ] ) {
5280 itemOffset
= $optionWidget
.offset();
5281 itemBoundingRect
= $optionWidget
[ 0 ].getBoundingClientRect();
5282 itemPosition
= $optionWidget
.position();
5283 itemIndex
= $optionWidget
.data( 'index' );
5288 this.isDragging() &&
5289 itemIndex
!== this.getDragItem().getIndex()
5291 if ( this.orientation
=== 'horizontal' ) {
5292 // Calculate where the mouse is relative to the item width
5293 itemSize
= itemBoundingRect
.width
;
5294 itemMidpoint
= itemBoundingRect
.left
+ itemSize
/ 2;
5295 dragPosition
= clientX
;
5296 // Which side of the item we hover over will dictate
5297 // where the placeholder will appear, on the left or
5300 left
: dragPosition
< itemMidpoint
? itemPosition
.left
: itemPosition
.left
+ itemSize
,
5301 top
: itemPosition
.top
5304 // Calculate where the mouse is relative to the item height
5305 itemSize
= itemBoundingRect
.height
;
5306 itemMidpoint
= itemBoundingRect
.top
+ itemSize
/ 2;
5307 dragPosition
= clientY
;
5308 // Which side of the item we hover over will dictate
5309 // where the placeholder will appear, on the top or
5312 top
: dragPosition
< itemMidpoint
? itemPosition
.top
: itemPosition
.top
+ itemSize
,
5313 left
: itemPosition
.left
5316 // Store whether we are before or after an item to rearrange
5317 // For horizontal layout, we need to account for RTL, as this is flipped
5318 if ( this.orientation
=== 'horizontal' && this.$element
.css( 'direction' ) === 'rtl' ) {
5319 this.sideInsertion
= dragPosition
< itemMidpoint
? 'after' : 'before';
5321 this.sideInsertion
= dragPosition
< itemMidpoint
? 'before' : 'after';
5323 // Add drop indicator between objects
5326 .removeClass( 'oo-ui-element-hidden' );
5328 // This means the item was dragged outside the widget
5331 .addClass( 'oo-ui-element-hidden' );
5338 * Set a dragged item
5340 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5342 OO
.ui
.mixin
.DraggableGroupElement
.prototype.setDragItem = function ( item
) {
5343 this.dragItem
= item
;
5347 * Unset the current dragged item
5349 OO
.ui
.mixin
.DraggableGroupElement
.prototype.unsetDragItem = function () {
5350 this.dragItem
= null;
5351 this.itemDragOver
= null;
5352 this.$placeholder
.addClass( 'oo-ui-element-hidden' );
5353 this.sideInsertion
= '';
5357 * Get the item that is currently being dragged.
5359 * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
5361 OO
.ui
.mixin
.DraggableGroupElement
.prototype.getDragItem = function () {
5362 return this.dragItem
;
5366 * Check if an item in the group is currently being dragged.
5368 * @return {Boolean} Item is being dragged
5370 OO
.ui
.mixin
.DraggableGroupElement
.prototype.isDragging = function () {
5371 return this.getDragItem() !== null;
5375 * IconElement is often mixed into other classes to generate an icon.
5376 * Icons are graphics, about the size of normal text. They are used to aid the user
5377 * in locating a control or to convey information in a space-efficient way. See the
5378 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
5379 * included in the library.
5381 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5387 * @param {Object} [config] Configuration options
5388 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
5389 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
5390 * the icon element be set to an existing icon instead of the one generated by this class, set a
5391 * value using a jQuery selection. For example:
5393 * // Use a <div> tag instead of a <span>
5395 * // Use an existing icon element instead of the one generated by the class
5396 * $icon: this.$element
5397 * // Use an icon element from a child widget
5398 * $icon: this.childwidget.$element
5399 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
5400 * symbolic names. A map is used for i18n purposes and contains a `default` icon
5401 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
5402 * by the user's language.
5404 * Example of an i18n map:
5406 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5407 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
5408 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5409 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
5410 * text. The icon title is displayed when users move the mouse over the icon.
5412 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
5413 // Configuration initialization
5414 config
= config
|| {};
5419 this.iconTitle
= null;
5422 this.setIcon( config
.icon
|| this.constructor.static.icon
);
5423 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
5424 this.setIconElement( config
.$icon
|| $( '<span>' ) );
5429 OO
.initClass( OO
.ui
.mixin
.IconElement
);
5431 /* Static Properties */
5434 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
5435 * for i18n purposes and contains a `default` icon name and additional names keyed by
5436 * language code. The `default` name is used when no icon is keyed by the user's language.
5438 * Example of an i18n map:
5440 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5442 * Note: the static property will be overridden if the #icon configuration is used.
5446 * @property {Object|string}
5448 OO
.ui
.mixin
.IconElement
.static.icon
= null;
5451 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5452 * function that returns title text, or `null` for no title.
5454 * The static property will be overridden if the #iconTitle configuration is used.
5458 * @property {string|Function|null}
5460 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
5465 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5466 * applies to the specified icon element instead of the one created by the class. If an icon
5467 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5468 * and mixin methods will no longer affect the element.
5470 * @param {jQuery} $icon Element to use as icon
5472 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
5475 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
5476 .removeAttr( 'title' );
5480 .addClass( 'oo-ui-iconElement-icon' )
5481 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
5482 if ( this.iconTitle
!== null ) {
5483 this.$icon
.attr( 'title', this.iconTitle
);
5486 this.updateThemeClasses();
5490 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5491 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5494 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5495 * by language code, or `null` to remove the icon.
5498 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
5499 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
5500 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
5502 if ( this.icon
!== icon
) {
5504 if ( this.icon
!== null ) {
5505 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
5507 if ( icon
!== null ) {
5508 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
5514 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
5515 this.updateThemeClasses();
5521 * Set the icon title. Use `null` to remove the title.
5523 * @param {string|Function|null} iconTitle A text string used as the icon title,
5524 * a function that returns title text, or `null` for no title.
5527 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
5528 iconTitle
= typeof iconTitle
=== 'function' ||
5529 ( typeof iconTitle
=== 'string' && iconTitle
.length
) ?
5530 OO
.ui
.resolveMsg( iconTitle
) : null;
5532 if ( this.iconTitle
!== iconTitle
) {
5533 this.iconTitle
= iconTitle
;
5535 if ( this.iconTitle
!== null ) {
5536 this.$icon
.attr( 'title', iconTitle
);
5538 this.$icon
.removeAttr( 'title' );
5547 * Get the symbolic name of the icon.
5549 * @return {string} Icon name
5551 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
5556 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5558 * @return {string} Icon title text
5560 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
5561 return this.iconTitle
;
5565 * IndicatorElement is often mixed into other classes to generate an indicator.
5566 * Indicators are small graphics that are generally used in two ways:
5568 * - To draw attention to the status of an item. For example, an indicator might be
5569 * used to show that an item in a list has errors that need to be resolved.
5570 * - To clarify the function of a control that acts in an exceptional way (a button
5571 * that opens a menu instead of performing an action directly, for example).
5573 * For a list of indicators included in the library, please see the
5574 * [OOjs UI documentation on MediaWiki] [1].
5576 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5582 * @param {Object} [config] Configuration options
5583 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5584 * configuration is omitted, the indicator element will use a generated `<span>`.
5585 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5586 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5588 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5589 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5590 * or a function that returns title text. The indicator title is displayed when users move
5591 * the mouse over the indicator.
5593 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
5594 // Configuration initialization
5595 config
= config
|| {};
5598 this.$indicator
= null;
5599 this.indicator
= null;
5600 this.indicatorTitle
= null;
5603 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
5604 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
5605 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
5610 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
5612 /* Static Properties */
5615 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5616 * The static property will be overridden if the #indicator configuration is used.
5620 * @property {string|null}
5622 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
5625 * A text string used as the indicator title, a function that returns title text, or `null`
5626 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5630 * @property {string|Function|null}
5632 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
5637 * Set the indicator element.
5639 * If an element is already set, it will be cleaned up before setting up the new element.
5641 * @param {jQuery} $indicator Element to use as indicator
5643 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
5644 if ( this.$indicator
) {
5646 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
5647 .removeAttr( 'title' );
5650 this.$indicator
= $indicator
5651 .addClass( 'oo-ui-indicatorElement-indicator' )
5652 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
5653 if ( this.indicatorTitle
!== null ) {
5654 this.$indicator
.attr( 'title', this.indicatorTitle
);
5657 this.updateThemeClasses();
5661 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5663 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5666 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
5667 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
5669 if ( this.indicator
!== indicator
) {
5670 if ( this.$indicator
) {
5671 if ( this.indicator
!== null ) {
5672 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
5674 if ( indicator
!== null ) {
5675 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
5678 this.indicator
= indicator
;
5681 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
5682 this.updateThemeClasses();
5688 * Set the indicator title.
5690 * The title is displayed when a user moves the mouse over the indicator.
5692 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5693 * `null` for no indicator title
5696 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
5697 indicatorTitle
= typeof indicatorTitle
=== 'function' ||
5698 ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ?
5699 OO
.ui
.resolveMsg( indicatorTitle
) : null;
5701 if ( this.indicatorTitle
!== indicatorTitle
) {
5702 this.indicatorTitle
= indicatorTitle
;
5703 if ( this.$indicator
) {
5704 if ( this.indicatorTitle
!== null ) {
5705 this.$indicator
.attr( 'title', indicatorTitle
);
5707 this.$indicator
.removeAttr( 'title' );
5716 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5718 * @return {string} Symbolic name of indicator
5720 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
5721 return this.indicator
;
5725 * Get the indicator title.
5727 * The title is displayed when a user moves the mouse over the indicator.
5729 * @return {string} Indicator title text
5731 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
5732 return this.indicatorTitle
;
5736 * LabelElement is often mixed into other classes to generate a label, which
5737 * helps identify the function of an interface element.
5738 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5740 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5746 * @param {Object} [config] Configuration options
5747 * @cfg {jQuery} [$label] The label element created by the class. If this
5748 * configuration is omitted, the label element will use a generated `<span>`.
5749 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
5750 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
5751 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
5752 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5753 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5754 * The label will be truncated to fit if necessary.
5756 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
5757 // Configuration initialization
5758 config
= config
|| {};
5763 this.autoFitLabel
= config
.autoFitLabel
=== undefined || !!config
.autoFitLabel
;
5766 this.setLabel( config
.label
|| this.constructor.static.label
);
5767 this.setLabelElement( config
.$label
|| $( '<span>' ) );
5772 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
5777 * @event labelChange
5778 * @param {string} value
5781 /* Static Properties */
5784 * The label text. The label can be specified as a plaintext string, a function that will
5785 * produce a string in the future, or `null` for no label. The static value will
5786 * be overridden if a label is specified with the #label config option.
5790 * @property {string|Function|null}
5792 OO
.ui
.mixin
.LabelElement
.static.label
= null;
5797 * Set the label element.
5799 * If an element is already set, it will be cleaned up before setting up the new element.
5801 * @param {jQuery} $label Element to use as label
5803 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
5804 if ( this.$label
) {
5805 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
5808 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
5809 this.setLabelContent( this.label
);
5815 * An empty string will result in the label being hidden. A string containing only whitespace will
5816 * be converted to a single ` `.
5818 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5819 * text; or null for no label
5822 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
5823 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
5824 label
= ( ( typeof label
=== 'string' && label
.length
) || label
instanceof jQuery
|| label
instanceof OO
.ui
.HtmlSnippet
) ? label
: null;
5826 this.$element
.toggleClass( 'oo-ui-labelElement', !!label
);
5828 if ( this.label
!== label
) {
5829 if ( this.$label
) {
5830 this.setLabelContent( label
);
5833 this.emit( 'labelChange' );
5842 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5843 * text; or null for no label
5845 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
5854 OO
.ui
.mixin
.LabelElement
.prototype.fitLabel = function () {
5855 if ( this.$label
&& this.$label
.autoEllipsis
&& this.autoFitLabel
) {
5856 this.$label
.autoEllipsis( { hasSpan
: false, tooltip
: true } );
5863 * Set the content of the label.
5865 * Do not call this method until after the label element has been set by #setLabelElement.
5868 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5869 * text; or null for no label
5871 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
5872 if ( typeof label
=== 'string' ) {
5873 if ( label
.match( /^\s*$/ ) ) {
5874 // Convert whitespace only string to a single non-breaking space
5875 this.$label
.html( ' ' );
5877 this.$label
.text( label
);
5879 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
5880 this.$label
.html( label
.toString() );
5881 } else if ( label
instanceof jQuery
) {
5882 this.$label
.empty().append( label
);
5884 this.$label
.empty();
5889 * LookupElement is a mixin that creates a {@link OO.ui.FloatingMenuSelectWidget menu} of suggested values for
5890 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
5891 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
5892 * from the lookup menu, that value becomes the value of the input field.
5894 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
5895 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
5896 * re-enable lookups.
5898 * See the [OOjs UI demos][1] for an example.
5900 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
5906 * @param {Object} [config] Configuration options
5907 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
5908 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
5909 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
5910 * By default, the lookup menu is not generated and displayed until the user begins to type.
5912 OO
.ui
.mixin
.LookupElement
= function OoUiMixinLookupElement( config
) {
5913 // Configuration initialization
5914 config
= config
|| {};
5917 this.$overlay
= config
.$overlay
|| this.$element
;
5918 this.lookupMenu
= new OO
.ui
.FloatingMenuSelectWidget( {
5921 $container
: config
.$container
|| this.$element
5924 this.allowSuggestionsWhenEmpty
= config
.allowSuggestionsWhenEmpty
|| false;
5926 this.lookupCache
= {};
5927 this.lookupQuery
= null;
5928 this.lookupRequest
= null;
5929 this.lookupsDisabled
= false;
5930 this.lookupInputFocused
= false;
5934 focus
: this.onLookupInputFocus
.bind( this ),
5935 blur
: this.onLookupInputBlur
.bind( this ),
5936 mousedown
: this.onLookupInputMouseDown
.bind( this )
5938 this.connect( this, { change
: 'onLookupInputChange' } );
5939 this.lookupMenu
.connect( this, {
5940 toggle
: 'onLookupMenuToggle',
5941 choose
: 'onLookupMenuItemChoose'
5945 this.$element
.addClass( 'oo-ui-lookupElement' );
5946 this.lookupMenu
.$element
.addClass( 'oo-ui-lookupElement-menu' );
5947 this.$overlay
.append( this.lookupMenu
.$element
);
5953 * Handle input focus event.
5956 * @param {jQuery.Event} e Input focus event
5958 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputFocus = function () {
5959 this.lookupInputFocused
= true;
5960 this.populateLookupMenu();
5964 * Handle input blur event.
5967 * @param {jQuery.Event} e Input blur event
5969 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputBlur = function () {
5970 this.closeLookupMenu();
5971 this.lookupInputFocused
= false;
5975 * Handle input mouse down event.
5978 * @param {jQuery.Event} e Input mouse down event
5980 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputMouseDown = function () {
5981 // Only open the menu if the input was already focused.
5982 // This way we allow the user to open the menu again after closing it with Esc
5983 // by clicking in the input. Opening (and populating) the menu when initially
5984 // clicking into the input is handled by the focus handler.
5985 if ( this.lookupInputFocused
&& !this.lookupMenu
.isVisible() ) {
5986 this.populateLookupMenu();
5991 * Handle input change event.
5994 * @param {string} value New input value
5996 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputChange = function () {
5997 if ( this.lookupInputFocused
) {
5998 this.populateLookupMenu();
6003 * Handle the lookup menu being shown/hidden.
6006 * @param {boolean} visible Whether the lookup menu is now visible.
6008 OO
.ui
.mixin
.LookupElement
.prototype.onLookupMenuToggle = function ( visible
) {
6010 // When the menu is hidden, abort any active request and clear the menu.
6011 // This has to be done here in addition to closeLookupMenu(), because
6012 // MenuSelectWidget will close itself when the user presses Esc.
6013 this.abortLookupRequest();
6014 this.lookupMenu
.clearItems();
6019 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
6022 * @param {OO.ui.MenuOptionWidget} item Selected item
6024 OO
.ui
.mixin
.LookupElement
.prototype.onLookupMenuItemChoose = function ( item
) {
6025 this.setValue( item
.getData() );
6032 * @return {OO.ui.FloatingMenuSelectWidget}
6034 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenu = function () {
6035 return this.lookupMenu
;
6039 * Disable or re-enable lookups.
6041 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
6043 * @param {boolean} disabled Disable lookups
6045 OO
.ui
.mixin
.LookupElement
.prototype.setLookupsDisabled = function ( disabled
) {
6046 this.lookupsDisabled
= !!disabled
;
6050 * Open the menu. If there are no entries in the menu, this does nothing.
6055 OO
.ui
.mixin
.LookupElement
.prototype.openLookupMenu = function () {
6056 if ( !this.lookupMenu
.isEmpty() ) {
6057 this.lookupMenu
.toggle( true );
6063 * Close the menu, empty it, and abort any pending request.
6068 OO
.ui
.mixin
.LookupElement
.prototype.closeLookupMenu = function () {
6069 this.lookupMenu
.toggle( false );
6070 this.abortLookupRequest();
6071 this.lookupMenu
.clearItems();
6076 * Request menu items based on the input's current value, and when they arrive,
6077 * populate the menu with these items and show the menu.
6079 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
6084 OO
.ui
.mixin
.LookupElement
.prototype.populateLookupMenu = function () {
6086 value
= this.getValue();
6088 if ( this.lookupsDisabled
|| this.isReadOnly() ) {
6092 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
6093 if ( !this.allowSuggestionsWhenEmpty
&& value
=== '' ) {
6094 this.closeLookupMenu();
6095 // Skip population if there is already a request pending for the current value
6096 } else if ( value
!== this.lookupQuery
) {
6097 this.getLookupMenuItems()
6098 .done( function ( items
) {
6099 widget
.lookupMenu
.clearItems();
6100 if ( items
.length
) {
6104 widget
.initializeLookupMenuSelection();
6106 widget
.lookupMenu
.toggle( false );
6109 .fail( function () {
6110 widget
.lookupMenu
.clearItems();
6118 * Highlight the first selectable item in the menu.
6123 OO
.ui
.mixin
.LookupElement
.prototype.initializeLookupMenuSelection = function () {
6124 if ( !this.lookupMenu
.getSelectedItem() ) {
6125 this.lookupMenu
.highlightItem( this.lookupMenu
.getFirstSelectableItem() );
6130 * Get lookup menu items for the current query.
6133 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
6134 * the done event. If the request was aborted to make way for a subsequent request, this promise
6135 * will not be rejected: it will remain pending forever.
6137 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenuItems = function () {
6139 value
= this.getValue(),
6140 deferred
= $.Deferred(),
6143 this.abortLookupRequest();
6144 if ( Object
.prototype.hasOwnProperty
.call( this.lookupCache
, value
) ) {
6145 deferred
.resolve( this.getLookupMenuOptionsFromData( this.lookupCache
[ value
] ) );
6148 this.lookupQuery
= value
;
6149 ourRequest
= this.lookupRequest
= this.getLookupRequest();
6151 .always( function () {
6152 // We need to pop pending even if this is an old request, otherwise
6153 // the widget will remain pending forever.
6154 // TODO: this assumes that an aborted request will fail or succeed soon after
6155 // being aborted, or at least eventually. It would be nice if we could popPending()
6156 // at abort time, but only if we knew that we hadn't already called popPending()
6157 // for that request.
6158 widget
.popPending();
6160 .done( function ( response
) {
6161 // If this is an old request (and aborting it somehow caused it to still succeed),
6162 // ignore its success completely
6163 if ( ourRequest
=== widget
.lookupRequest
) {
6164 widget
.lookupQuery
= null;
6165 widget
.lookupRequest
= null;
6166 widget
.lookupCache
[ value
] = widget
.getLookupCacheDataFromResponse( response
);
6167 deferred
.resolve( widget
.getLookupMenuOptionsFromData( widget
.lookupCache
[ value
] ) );
6170 .fail( function () {
6171 // If this is an old request (or a request failing because it's being aborted),
6172 // ignore its failure completely
6173 if ( ourRequest
=== widget
.lookupRequest
) {
6174 widget
.lookupQuery
= null;
6175 widget
.lookupRequest
= null;
6180 return deferred
.promise();
6184 * Abort the currently pending lookup request, if any.
6188 OO
.ui
.mixin
.LookupElement
.prototype.abortLookupRequest = function () {
6189 var oldRequest
= this.lookupRequest
;
6191 // First unset this.lookupRequest to the fail handler will notice
6192 // that the request is no longer current
6193 this.lookupRequest
= null;
6194 this.lookupQuery
= null;
6200 * Get a new request object of the current lookup query value.
6204 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
6206 OO
.ui
.mixin
.LookupElement
.prototype.getLookupRequest = function () {
6207 // Stub, implemented in subclass
6212 * Pre-process data returned by the request from #getLookupRequest.
6214 * The return value of this function will be cached, and any further queries for the given value
6215 * will use the cache rather than doing API requests.
6219 * @param {Mixed} response Response from server
6220 * @return {Mixed} Cached result data
6222 OO
.ui
.mixin
.LookupElement
.prototype.getLookupCacheDataFromResponse = function () {
6223 // Stub, implemented in subclass
6228 * Get a list of menu option widgets from the (possibly cached) data returned by
6229 * #getLookupCacheDataFromResponse.
6233 * @param {Mixed} data Cached result data, usually an array
6234 * @return {OO.ui.MenuOptionWidget[]} Menu items
6236 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenuOptionsFromData = function () {
6237 // Stub, implemented in subclass
6242 * Set the read-only state of the widget.
6244 * This will also disable/enable the lookups functionality.
6246 * @param {boolean} readOnly Make input read-only
6249 OO
.ui
.mixin
.LookupElement
.prototype.setReadOnly = function ( readOnly
) {
6251 // Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget
6252 OO
.ui
.TextInputWidget
.prototype.setReadOnly
.call( this, readOnly
);
6254 // During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor
6255 if ( this.isReadOnly() && this.lookupMenu
) {
6256 this.closeLookupMenu();
6263 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
6264 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
6265 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
6266 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
6272 * @param {Object} [config] Configuration options
6273 * @cfg {Object} [popup] Configuration to pass to popup
6274 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
6276 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
6277 // Configuration initialization
6278 config
= config
|| {};
6281 this.popup
= new OO
.ui
.PopupWidget( $.extend(
6282 { autoClose
: true },
6284 { $autoCloseIgnore
: this.$element
}
6293 * @return {OO.ui.PopupWidget} Popup widget
6295 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
6300 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
6301 * additional functionality to an element created by another class. The class provides
6302 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
6303 * which are used to customize the look and feel of a widget to better describe its
6304 * importance and functionality.
6306 * The library currently contains the following styling flags for general use:
6308 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
6309 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
6310 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
6312 * The flags affect the appearance of the buttons:
6315 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
6316 * var button1 = new OO.ui.ButtonWidget( {
6317 * label: 'Constructive',
6318 * flags: 'constructive'
6320 * var button2 = new OO.ui.ButtonWidget( {
6321 * label: 'Destructive',
6322 * flags: 'destructive'
6324 * var button3 = new OO.ui.ButtonWidget( {
6325 * label: 'Progressive',
6326 * flags: 'progressive'
6328 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
6330 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
6331 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6333 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6339 * @param {Object} [config] Configuration options
6340 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
6341 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
6342 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6343 * @cfg {jQuery} [$flagged] The flagged element. By default,
6344 * the flagged functionality is applied to the element created by the class ($element).
6345 * If a different element is specified, the flagged functionality will be applied to it instead.
6347 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
6348 // Configuration initialization
6349 config
= config
|| {};
6353 this.$flagged
= null;
6356 this.setFlags( config
.flags
);
6357 this.setFlaggedElement( config
.$flagged
|| this.$element
);
6364 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
6365 * parameter contains the name of each modified flag and indicates whether it was
6368 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
6369 * that the flag was added, `false` that the flag was removed.
6375 * Set the flagged element.
6377 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
6378 * If an element is already set, the method will remove the mixin’s effect on that element.
6380 * @param {jQuery} $flagged Element that should be flagged
6382 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
6383 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
6384 return 'oo-ui-flaggedElement-' + flag
;
6387 if ( this.$flagged
) {
6388 this.$flagged
.removeClass( classNames
);
6391 this.$flagged
= $flagged
.addClass( classNames
);
6395 * Check if the specified flag is set.
6397 * @param {string} flag Name of flag
6398 * @return {boolean} The flag is set
6400 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
6401 // This may be called before the constructor, thus before this.flags is set
6402 return this.flags
&& ( flag
in this.flags
);
6406 * Get the names of all flags set.
6408 * @return {string[]} Flag names
6410 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
6411 // This may be called before the constructor, thus before this.flags is set
6412 return Object
.keys( this.flags
|| {} );
6421 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
6422 var flag
, className
,
6425 classPrefix
= 'oo-ui-flaggedElement-';
6427 for ( flag
in this.flags
) {
6428 className
= classPrefix
+ flag
;
6429 changes
[ flag
] = false;
6430 delete this.flags
[ flag
];
6431 remove
.push( className
);
6434 if ( this.$flagged
) {
6435 this.$flagged
.removeClass( remove
.join( ' ' ) );
6438 this.updateThemeClasses();
6439 this.emit( 'flag', changes
);
6445 * Add one or more flags.
6447 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
6448 * or an object keyed by flag name with a boolean value that indicates whether the flag should
6449 * be added (`true`) or removed (`false`).
6453 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
6454 var i
, len
, flag
, className
,
6458 classPrefix
= 'oo-ui-flaggedElement-';
6460 if ( typeof flags
=== 'string' ) {
6461 className
= classPrefix
+ flags
;
6463 if ( !this.flags
[ flags
] ) {
6464 this.flags
[ flags
] = true;
6465 add
.push( className
);
6467 } else if ( Array
.isArray( flags
) ) {
6468 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
6470 className
= classPrefix
+ flag
;
6472 if ( !this.flags
[ flag
] ) {
6473 changes
[ flag
] = true;
6474 this.flags
[ flag
] = true;
6475 add
.push( className
);
6478 } else if ( OO
.isPlainObject( flags
) ) {
6479 for ( flag
in flags
) {
6480 className
= classPrefix
+ flag
;
6481 if ( flags
[ flag
] ) {
6483 if ( !this.flags
[ flag
] ) {
6484 changes
[ flag
] = true;
6485 this.flags
[ flag
] = true;
6486 add
.push( className
);
6490 if ( this.flags
[ flag
] ) {
6491 changes
[ flag
] = false;
6492 delete this.flags
[ flag
];
6493 remove
.push( className
);
6499 if ( this.$flagged
) {
6501 .addClass( add
.join( ' ' ) )
6502 .removeClass( remove
.join( ' ' ) );
6505 this.updateThemeClasses();
6506 this.emit( 'flag', changes
);
6512 * TitledElement is mixed into other classes to provide a `title` attribute.
6513 * Titles are rendered by the browser and are made visible when the user moves
6514 * the mouse over the element. Titles are not visible on touch devices.
6517 * // TitledElement provides a 'title' attribute to the
6518 * // ButtonWidget class
6519 * var button = new OO.ui.ButtonWidget( {
6520 * label: 'Button with Title',
6521 * title: 'I am a button'
6523 * $( 'body' ).append( button.$element );
6529 * @param {Object} [config] Configuration options
6530 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6531 * If this config is omitted, the title functionality is applied to $element, the
6532 * element created by the class.
6533 * @cfg {string|Function} [title] The title text or a function that returns text. If
6534 * this config is omitted, the value of the {@link #static-title static title} property is used.
6536 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
6537 // Configuration initialization
6538 config
= config
|| {};
6541 this.$titled
= null;
6545 this.setTitle( config
.title
|| this.constructor.static.title
);
6546 this.setTitledElement( config
.$titled
|| this.$element
);
6551 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
6553 /* Static Properties */
6556 * The title text, a function that returns text, or `null` for no title. The value of the static property
6557 * is overridden if the #title config option is used.
6561 * @property {string|Function|null}
6563 OO
.ui
.mixin
.TitledElement
.static.title
= null;
6568 * Set the titled element.
6570 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6571 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6573 * @param {jQuery} $titled Element that should use the 'titled' functionality
6575 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
6576 if ( this.$titled
) {
6577 this.$titled
.removeAttr( 'title' );
6580 this.$titled
= $titled
;
6582 this.$titled
.attr( 'title', this.title
);
6589 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6592 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
6593 title
= typeof title
=== 'string' ? OO
.ui
.resolveMsg( title
) : null;
6595 if ( this.title
!== title
) {
6596 if ( this.$titled
) {
6597 if ( title
!== null ) {
6598 this.$titled
.attr( 'title', title
);
6600 this.$titled
.removeAttr( 'title' );
6612 * @return {string} Title string
6614 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
6619 * Element that can be automatically clipped to visible boundaries.
6621 * Whenever the element's natural height changes, you have to call
6622 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
6623 * clipping correctly.
6625 * The dimensions of #$clippableContainer will be compared to the boundaries of the
6626 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
6627 * then #$clippable will be given a fixed reduced height and/or width and will be made
6628 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
6629 * but you can build a static footer by setting #$clippableContainer to an element that contains
6630 * #$clippable and the footer.
6636 * @param {Object} [config] Configuration options
6637 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
6638 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
6639 * omit to use #$clippable
6641 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
6642 // Configuration initialization
6643 config
= config
|| {};
6646 this.$clippable
= null;
6647 this.$clippableContainer
= null;
6648 this.clipping
= false;
6649 this.clippedHorizontally
= false;
6650 this.clippedVertically
= false;
6651 this.$clippableScrollableContainer
= null;
6652 this.$clippableScroller
= null;
6653 this.$clippableWindow
= null;
6654 this.idealWidth
= null;
6655 this.idealHeight
= null;
6656 this.onClippableScrollHandler
= this.clip
.bind( this );
6657 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
6660 if ( config
.$clippableContainer
) {
6661 this.setClippableContainer( config
.$clippableContainer
);
6663 this.setClippableElement( config
.$clippable
|| this.$element
);
6669 * Set clippable element.
6671 * If an element is already set, it will be cleaned up before setting up the new element.
6673 * @param {jQuery} $clippable Element to make clippable
6675 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
6676 if ( this.$clippable
) {
6677 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
6678 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6679 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6682 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
6687 * Set clippable container.
6689 * This is the container that will be measured when deciding whether to clip. When clipping,
6690 * #$clippable will be resized in order to keep the clippable container fully visible.
6692 * If the clippable container is unset, #$clippable will be used.
6694 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
6696 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableContainer = function ( $clippableContainer
) {
6697 this.$clippableContainer
= $clippableContainer
;
6698 if ( this.$clippable
) {
6706 * Do not turn clipping on until after the element is attached to the DOM and visible.
6708 * @param {boolean} [clipping] Enable clipping, omit to toggle
6711 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
6712 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
6714 if ( this.clipping
!== clipping
) {
6715 this.clipping
= clipping
;
6717 this.$clippableScrollableContainer
= $( this.getClosestScrollableElementContainer() );
6718 // If the clippable container is the root, we have to listen to scroll events and check
6719 // jQuery.scrollTop on the window because of browser inconsistencies
6720 this.$clippableScroller
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
6721 $( OO
.ui
.Element
.static.getWindow( this.$clippableScrollableContainer
) ) :
6722 this.$clippableScrollableContainer
;
6723 this.$clippableScroller
.on( 'scroll', this.onClippableScrollHandler
);
6724 this.$clippableWindow
= $( this.getElementWindow() )
6725 .on( 'resize', this.onClippableWindowResizeHandler
);
6726 // Initial clip after visible
6729 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6730 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6732 this.$clippableScrollableContainer
= null;
6733 this.$clippableScroller
.off( 'scroll', this.onClippableScrollHandler
);
6734 this.$clippableScroller
= null;
6735 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
6736 this.$clippableWindow
= null;
6744 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6746 * @return {boolean} Element will be clipped to the visible area
6748 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
6749 return this.clipping
;
6753 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6755 * @return {boolean} Part of the element is being clipped
6757 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
6758 return this.clippedHorizontally
|| this.clippedVertically
;
6762 * Check if the right of the element is being clipped by the nearest scrollable container.
6764 * @return {boolean} Part of the element is being clipped
6766 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
6767 return this.clippedHorizontally
;
6771 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6773 * @return {boolean} Part of the element is being clipped
6775 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
6776 return this.clippedVertically
;
6780 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6782 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6783 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6785 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
6786 this.idealWidth
= width
;
6787 this.idealHeight
= height
;
6789 if ( !this.clipping
) {
6790 // Update dimensions
6791 this.$clippable
.css( { width
: width
, height
: height
} );
6793 // While clipping, idealWidth and idealHeight are not considered
6797 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6798 * the element's natural height changes.
6800 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6801 * overlapped by, the visible area of the nearest scrollable container.
6805 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
6806 var $container
, extraHeight
, extraWidth
, ccOffset
,
6807 $scrollableContainer
, scOffset
, scHeight
, scWidth
,
6808 ccWidth
, scrollerIsWindow
, scrollTop
, scrollLeft
,
6809 desiredWidth
, desiredHeight
, allotedWidth
, allotedHeight
,
6810 naturalWidth
, naturalHeight
, clipWidth
, clipHeight
,
6811 buffer
= 7; // Chosen by fair dice roll
6813 if ( !this.clipping
) {
6814 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
6818 $container
= this.$clippableContainer
|| this.$clippable
;
6819 extraHeight
= $container
.outerHeight() - this.$clippable
.outerHeight();
6820 extraWidth
= $container
.outerWidth() - this.$clippable
.outerWidth();
6821 ccOffset
= $container
.offset();
6822 $scrollableContainer
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
6823 this.$clippableWindow
: this.$clippableScrollableContainer
;
6824 scOffset
= $scrollableContainer
.offset() || { top
: 0, left
: 0 };
6825 scHeight
= $scrollableContainer
.innerHeight() - buffer
;
6826 scWidth
= $scrollableContainer
.innerWidth() - buffer
;
6827 ccWidth
= $container
.outerWidth() + buffer
;
6828 scrollerIsWindow
= this.$clippableScroller
[ 0 ] === this.$clippableWindow
[ 0 ];
6829 scrollTop
= scrollerIsWindow
? this.$clippableScroller
.scrollTop() : 0;
6830 scrollLeft
= scrollerIsWindow
? this.$clippableScroller
.scrollLeft() : 0;
6831 desiredWidth
= ccOffset
.left
< 0 ?
6832 ccWidth
+ ccOffset
.left
:
6833 ( scOffset
.left
+ scrollLeft
+ scWidth
) - ccOffset
.left
;
6834 desiredHeight
= ( scOffset
.top
+ scrollTop
+ scHeight
) - ccOffset
.top
;
6835 allotedWidth
= desiredWidth
- extraWidth
;
6836 allotedHeight
= desiredHeight
- extraHeight
;
6837 naturalWidth
= this.$clippable
.prop( 'scrollWidth' );
6838 naturalHeight
= this.$clippable
.prop( 'scrollHeight' );
6839 clipWidth
= allotedWidth
< naturalWidth
;
6840 clipHeight
= allotedHeight
< naturalHeight
;
6843 this.$clippable
.css( { overflowX
: 'scroll', width
: Math
.max( 0, allotedWidth
) } );
6845 this.$clippable
.css( { width
: this.idealWidth
? this.idealWidth
- extraWidth
: '', overflowX
: '' } );
6848 this.$clippable
.css( { overflowY
: 'scroll', height
: Math
.max( 0, allotedHeight
) } );
6850 this.$clippable
.css( { height
: this.idealHeight
? this.idealHeight
- extraHeight
: '', overflowY
: '' } );
6853 // If we stopped clipping in at least one of the dimensions
6854 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
6855 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6858 this.clippedHorizontally
= clipWidth
;
6859 this.clippedVertically
= clipHeight
;
6865 * Element that will stick under a specified container, even when it is inserted elsewhere in the
6866 * document (for example, in a OO.ui.Window's $overlay).
6868 * The elements's position is automatically calculated and maintained when window is resized or the
6869 * page is scrolled. If you reposition the container manually, you have to call #position to make
6870 * sure the element is still placed correctly.
6872 * As positioning is only possible when both the element and the container are attached to the DOM
6873 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
6874 * the #toggle method to display a floating popup, for example.
6880 * @param {Object} [config] Configuration options
6881 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
6882 * @cfg {jQuery} [$floatableContainer] Node to position below
6884 OO
.ui
.mixin
.FloatableElement
= function OoUiMixinFloatableElement( config
) {
6885 // Configuration initialization
6886 config
= config
|| {};
6889 this.$floatable
= null;
6890 this.$floatableContainer
= null;
6891 this.$floatableWindow
= null;
6892 this.$floatableClosestScrollable
= null;
6893 this.onFloatableScrollHandler
= this.position
.bind( this );
6894 this.onFloatableWindowResizeHandler
= this.position
.bind( this );
6897 this.setFloatableContainer( config
.$floatableContainer
);
6898 this.setFloatableElement( config
.$floatable
|| this.$element
);
6904 * Set floatable element.
6906 * If an element is already set, it will be cleaned up before setting up the new element.
6908 * @param {jQuery} $floatable Element to make floatable
6910 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableElement = function ( $floatable
) {
6911 if ( this.$floatable
) {
6912 this.$floatable
.removeClass( 'oo-ui-floatableElement-floatable' );
6913 this.$floatable
.css( { left
: '', top
: '' } );
6916 this.$floatable
= $floatable
.addClass( 'oo-ui-floatableElement-floatable' );
6921 * Set floatable container.
6923 * The element will be always positioned under the specified container.
6925 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
6927 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableContainer = function ( $floatableContainer
) {
6928 this.$floatableContainer
= $floatableContainer
;
6929 if ( this.$floatable
) {
6935 * Toggle positioning.
6937 * Do not turn positioning on until after the element is attached to the DOM and visible.
6939 * @param {boolean} [positioning] Enable positioning, omit to toggle
6942 OO
.ui
.mixin
.FloatableElement
.prototype.togglePositioning = function ( positioning
) {
6943 var closestScrollableOfContainer
, closestScrollableOfFloatable
;
6945 positioning
= positioning
=== undefined ? !this.positioning
: !!positioning
;
6947 if ( this.positioning
!== positioning
) {
6948 this.positioning
= positioning
;
6950 closestScrollableOfContainer
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatableContainer
[ 0 ] );
6951 closestScrollableOfFloatable
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatable
[ 0 ] );
6952 if ( closestScrollableOfContainer
!== closestScrollableOfFloatable
) {
6953 // If the scrollable is the root, we have to listen to scroll events
6954 // on the window because of browser inconsistencies (or do we? someone should verify this)
6955 if ( $( closestScrollableOfContainer
).is( 'html, body' ) ) {
6956 closestScrollableOfContainer
= OO
.ui
.Element
.static.getWindow( closestScrollableOfContainer
);
6960 if ( positioning
) {
6961 this.$floatableWindow
= $( this.getElementWindow() );
6962 this.$floatableWindow
.on( 'resize', this.onFloatableWindowResizeHandler
);
6964 if ( closestScrollableOfContainer
!== closestScrollableOfFloatable
) {
6965 this.$floatableClosestScrollable
= $( closestScrollableOfContainer
);
6966 this.$floatableClosestScrollable
.on( 'scroll', this.onFloatableScrollHandler
);
6969 // Initial position after visible
6972 if ( this.$floatableWindow
) {
6973 this.$floatableWindow
.off( 'resize', this.onFloatableWindowResizeHandler
);
6974 this.$floatableWindow
= null;
6977 if ( this.$floatableClosestScrollable
) {
6978 this.$floatableClosestScrollable
.off( 'scroll', this.onFloatableScrollHandler
);
6979 this.$floatableClosestScrollable
= null;
6982 this.$floatable
.css( { left
: '', top
: '' } );
6990 * Position the floatable below its container.
6992 * This should only be done when both of them are attached to the DOM and visible.
6996 OO
.ui
.mixin
.FloatableElement
.prototype.position = function () {
6999 if ( !this.positioning
) {
7003 pos
= OO
.ui
.Element
.static.getRelativePosition( this.$floatableContainer
, this.$floatable
.offsetParent() );
7005 // Position under container
7006 pos
.top
+= this.$floatableContainer
.height();
7007 this.$floatable
.css( pos
);
7009 // We updated the position, so re-evaluate the clipping state.
7010 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
7011 // will not notice the need to update itself.)
7012 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
7013 // it not listen to the right events in the right places?
7022 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
7023 * Accesskeys allow an user to go to a specific element by using
7024 * a shortcut combination of a browser specific keys + the key
7028 * // AccessKeyedElement provides an 'accesskey' attribute to the
7029 * // ButtonWidget class
7030 * var button = new OO.ui.ButtonWidget( {
7031 * label: 'Button with Accesskey',
7034 * $( 'body' ).append( button.$element );
7040 * @param {Object} [config] Configuration options
7041 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
7042 * If this config is omitted, the accesskey functionality is applied to $element, the
7043 * element created by the class.
7044 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
7045 * this config is omitted, no accesskey will be added.
7047 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
7048 // Configuration initialization
7049 config
= config
|| {};
7052 this.$accessKeyed
= null;
7053 this.accessKey
= null;
7056 this.setAccessKey( config
.accessKey
|| null );
7057 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
7062 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
7064 /* Static Properties */
7067 * The access key, a function that returns a key, or `null` for no accesskey.
7071 * @property {string|Function|null}
7073 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
7078 * Set the accesskeyed element.
7080 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
7081 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
7083 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
7085 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
7086 if ( this.$accessKeyed
) {
7087 this.$accessKeyed
.removeAttr( 'accesskey' );
7090 this.$accessKeyed
= $accessKeyed
;
7091 if ( this.accessKey
) {
7092 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
7099 * @param {string|Function|null} accesskey Key, a function that returns a key, or `null` for no accesskey
7102 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
7103 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
7105 if ( this.accessKey
!== accessKey
) {
7106 if ( this.$accessKeyed
) {
7107 if ( accessKey
!== null ) {
7108 this.$accessKeyed
.attr( 'accesskey', accessKey
);
7110 this.$accessKeyed
.removeAttr( 'accesskey' );
7113 this.accessKey
= accessKey
;
7122 * @return {string} accessKey string
7124 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
7125 return this.accessKey
;
7129 * Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute {@link OO.ui.Toolbar toolbars}.
7130 * Each tool is configured with a static name, title, and icon and is customized with the command to carry
7131 * out when the tool is selected. Tools must also be registered with a {@link OO.ui.ToolFactory tool factory},
7132 * which creates the tools on demand.
7134 * Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup},
7135 * {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which determine how
7136 * the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an example.
7138 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
7139 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7143 * @extends OO.ui.Widget
7144 * @mixins OO.ui.mixin.IconElement
7145 * @mixins OO.ui.mixin.FlaggedElement
7146 * @mixins OO.ui.mixin.TabIndexedElement
7149 * @param {OO.ui.ToolGroup} toolGroup
7150 * @param {Object} [config] Configuration options
7151 * @cfg {string|Function} [title] Title text or a function that returns text. If this config is omitted, the value of
7152 * the {@link #static-title static title} property is used.
7154 * The title is used in different ways depending on the type of toolgroup that contains the tool. The
7155 * 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
7156 * part of a {@link OO.ui.ListToolGroup list} or {@link OO.ui.MenuToolGroup menu} toolgroup.
7158 * For bar toolgroups, a description of the accelerator key is appended to the title if an accelerator key
7159 * is associated with an action by the same name as the tool and accelerator functionality has been added to the application.
7160 * To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method.
7162 OO
.ui
.Tool
= function OoUiTool( toolGroup
, config
) {
7163 // Allow passing positional parameters inside the config object
7164 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
7166 toolGroup
= config
.toolGroup
;
7169 // Configuration initialization
7170 config
= config
|| {};
7172 // Parent constructor
7173 OO
.ui
.Tool
.parent
.call( this, config
);
7176 this.toolGroup
= toolGroup
;
7177 this.toolbar
= this.toolGroup
.getToolbar();
7178 this.active
= false;
7179 this.$title
= $( '<span>' );
7180 this.$accel
= $( '<span>' );
7181 this.$link
= $( '<a>' );
7184 // Mixin constructors
7185 OO
.ui
.mixin
.IconElement
.call( this, config
);
7186 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
7187 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$link
} ) );
7190 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
7193 this.$title
.addClass( 'oo-ui-tool-title' );
7195 .addClass( 'oo-ui-tool-accel' )
7197 // This may need to be changed if the key names are ever localized,
7198 // but for now they are essentially written in English
7203 .addClass( 'oo-ui-tool-link' )
7204 .append( this.$icon
, this.$title
, this.$accel
)
7205 .attr( 'role', 'button' );
7207 .data( 'oo-ui-tool', this )
7209 'oo-ui-tool ' + 'oo-ui-tool-name-' +
7210 this.constructor.static.name
.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
7212 .toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel
)
7213 .append( this.$link
);
7214 this.setTitle( config
.title
|| this.constructor.static.title
);
7219 OO
.inheritClass( OO
.ui
.Tool
, OO
.ui
.Widget
);
7220 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.IconElement
);
7221 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.FlaggedElement
);
7222 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.TabIndexedElement
);
7224 /* Static Properties */
7230 OO
.ui
.Tool
.static.tagName
= 'span';
7233 * Symbolic name of tool.
7235 * The symbolic name is used internally to register the tool with a {@link OO.ui.ToolFactory ToolFactory}. It can
7236 * also be used when adding tools to toolgroups.
7241 * @property {string}
7243 OO
.ui
.Tool
.static.name
= '';
7246 * Symbolic name of the group.
7248 * The group name is used to associate tools with each other so that they can be selected later by
7249 * a {@link OO.ui.ToolGroup toolgroup}.
7254 * @property {string}
7256 OO
.ui
.Tool
.static.group
= '';
7259 * 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.
7264 * @property {string|Function}
7266 OO
.ui
.Tool
.static.title
= '';
7269 * Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup.
7270 * Normally only the icon is displayed, or only the label if no icon is given.
7274 * @property {boolean}
7276 OO
.ui
.Tool
.static.displayBothIconAndLabel
= false;
7279 * Add tool to catch-all groups automatically.
7281 * A catch-all group, which contains all tools that do not currently belong to a toolgroup,
7282 * can be included in a toolgroup using the wildcard selector, an asterisk (*).
7286 * @property {boolean}
7288 OO
.ui
.Tool
.static.autoAddToCatchall
= true;
7291 * Add tool to named groups automatically.
7293 * By default, tools that are configured with a static ‘group’ property are added
7294 * to that group and will be selected when the symbolic name of the group is specified (e.g., when
7295 * toolgroups include tools by group name).
7298 * @property {boolean}
7301 OO
.ui
.Tool
.static.autoAddToGroup
= true;
7304 * Check if this tool is compatible with given data.
7306 * This is a stub that can be overriden to provide support for filtering tools based on an
7307 * arbitrary piece of information (e.g., where the cursor is in a document). The implementation
7308 * must also call this method so that the compatibility check can be performed.
7312 * @param {Mixed} data Data to check
7313 * @return {boolean} Tool can be used with data
7315 OO
.ui
.Tool
.static.isCompatibleWith = function () {
7322 * Handle the toolbar state being updated.
7324 * This is an abstract method that must be overridden in a concrete subclass.
7329 OO
.ui
.Tool
.prototype.onUpdateState = function () {
7331 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
7336 * Handle the tool being selected.
7338 * This is an abstract method that must be overridden in a concrete subclass.
7343 OO
.ui
.Tool
.prototype.onSelect = function () {
7345 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
7350 * Check if the tool is active.
7352 * Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed
7353 * with the #setActive method. Additional CSS is applied to the tool to reflect the active state.
7355 * @return {boolean} Tool is active
7357 OO
.ui
.Tool
.prototype.isActive = function () {
7362 * Make the tool appear active or inactive.
7364 * This method should be called within #onSelect or #onUpdateState event handlers to make the tool
7365 * appear pressed or not.
7367 * @param {boolean} state Make tool appear active
7369 OO
.ui
.Tool
.prototype.setActive = function ( state
) {
7370 this.active
= !!state
;
7371 if ( this.active
) {
7372 this.$element
.addClass( 'oo-ui-tool-active' );
7374 this.$element
.removeClass( 'oo-ui-tool-active' );
7379 * Set the tool #title.
7381 * @param {string|Function} title Title text or a function that returns text
7384 OO
.ui
.Tool
.prototype.setTitle = function ( title
) {
7385 this.title
= OO
.ui
.resolveMsg( title
);
7391 * Get the tool #title.
7393 * @return {string} Title text
7395 OO
.ui
.Tool
.prototype.getTitle = function () {
7400 * Get the tool's symbolic name.
7402 * @return {string} Symbolic name of tool
7404 OO
.ui
.Tool
.prototype.getName = function () {
7405 return this.constructor.static.name
;
7411 OO
.ui
.Tool
.prototype.updateTitle = function () {
7412 var titleTooltips
= this.toolGroup
.constructor.static.titleTooltips
,
7413 accelTooltips
= this.toolGroup
.constructor.static.accelTooltips
,
7414 accel
= this.toolbar
.getToolAccelerator( this.constructor.static.name
),
7417 this.$title
.text( this.title
);
7418 this.$accel
.text( accel
);
7420 if ( titleTooltips
&& typeof this.title
=== 'string' && this.title
.length
) {
7421 tooltipParts
.push( this.title
);
7423 if ( accelTooltips
&& typeof accel
=== 'string' && accel
.length
) {
7424 tooltipParts
.push( accel
);
7426 if ( tooltipParts
.length
) {
7427 this.$link
.attr( 'title', tooltipParts
.join( ' ' ) );
7429 this.$link
.removeAttr( 'title' );
7436 * Destroying the tool removes all event handlers and the tool’s DOM elements.
7437 * Call this method whenever you are done using a tool.
7439 OO
.ui
.Tool
.prototype.destroy = function () {
7440 this.toolbar
.disconnect( this );
7441 this.$element
.remove();
7445 * Toolbars are complex interface components that permit users to easily access a variety
7446 * of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional commands that are
7447 * part of the toolbar, but not configured as tools.
7449 * Individual tools are customized and then registered with a {@link OO.ui.ToolFactory tool factory}, which creates
7450 * the tools on demand. Each tool has a symbolic name (used when registering the tool), a title (e.g., ‘Insert
7451 * picture’), and an icon.
7453 * Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be {@link OO.ui.MenuToolGroup menus}
7454 * of tools, {@link OO.ui.ListToolGroup lists} of tools, or a single {@link OO.ui.BarToolGroup bar} of tools.
7455 * The arrangement and order of the toolgroups is customized when the toolbar is set up. Tools can be presented in
7456 * any order, but each can only appear once in the toolbar.
7458 * The following is an example of a basic toolbar.
7461 * // Example of a toolbar
7462 * // Create the toolbar
7463 * var toolFactory = new OO.ui.ToolFactory();
7464 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7465 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7467 * // We will be placing status text in this element when tools are used
7468 * var $area = $( '<p>' ).text( 'Toolbar example' );
7470 * // Define the tools that we're going to place in our toolbar
7472 * // Create a class inheriting from OO.ui.Tool
7473 * function PictureTool() {
7474 * PictureTool.parent.apply( this, arguments );
7476 * OO.inheritClass( PictureTool, OO.ui.Tool );
7477 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7478 * // of 'icon' and 'title' (displayed icon and text).
7479 * PictureTool.static.name = 'picture';
7480 * PictureTool.static.icon = 'picture';
7481 * PictureTool.static.title = 'Insert picture';
7482 * // Defines the action that will happen when this tool is selected (clicked).
7483 * PictureTool.prototype.onSelect = function () {
7484 * $area.text( 'Picture tool clicked!' );
7485 * // Never display this tool as "active" (selected).
7486 * this.setActive( false );
7488 * // Make this tool available in our toolFactory and thus our toolbar
7489 * toolFactory.register( PictureTool );
7491 * // Register two more tools, nothing interesting here
7492 * function SettingsTool() {
7493 * SettingsTool.parent.apply( this, arguments );
7495 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7496 * SettingsTool.static.name = 'settings';
7497 * SettingsTool.static.icon = 'settings';
7498 * SettingsTool.static.title = 'Change settings';
7499 * SettingsTool.prototype.onSelect = function () {
7500 * $area.text( 'Settings tool clicked!' );
7501 * this.setActive( false );
7503 * toolFactory.register( SettingsTool );
7505 * // Register two more tools, nothing interesting here
7506 * function StuffTool() {
7507 * StuffTool.parent.apply( this, arguments );
7509 * OO.inheritClass( StuffTool, OO.ui.Tool );
7510 * StuffTool.static.name = 'stuff';
7511 * StuffTool.static.icon = 'ellipsis';
7512 * StuffTool.static.title = 'More stuff';
7513 * StuffTool.prototype.onSelect = function () {
7514 * $area.text( 'More stuff tool clicked!' );
7515 * this.setActive( false );
7517 * toolFactory.register( StuffTool );
7519 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7520 * // little popup window (a PopupWidget).
7521 * function HelpTool( toolGroup, config ) {
7522 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7527 * this.popup.$body.append( '<p>I am helpful!</p>' );
7529 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7530 * HelpTool.static.name = 'help';
7531 * HelpTool.static.icon = 'help';
7532 * HelpTool.static.title = 'Help';
7533 * toolFactory.register( HelpTool );
7535 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7536 * // used once (but not all defined tools must be used).
7539 * // 'bar' tool groups display tools' icons only, side-by-side.
7541 * include: [ 'picture', 'help' ]
7544 * // 'list' tool groups display both the titles and icons, in a dropdown list.
7546 * indicator: 'down',
7548 * include: [ 'settings', 'stuff' ]
7550 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
7551 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here,
7552 * // since it's more complicated to use. (See the next example snippet on this page.)
7555 * // Create some UI around the toolbar and place it in the document
7556 * var frame = new OO.ui.PanelLayout( {
7560 * var contentFrame = new OO.ui.PanelLayout( {
7564 * frame.$element.append(
7566 * contentFrame.$element.append( $area )
7568 * $( 'body' ).append( frame.$element );
7570 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7572 * toolbar.initialize();
7574 * The following example extends the previous one to illustrate 'menu' toolgroups and the usage of
7575 * 'updateState' event.
7578 * // Create the toolbar
7579 * var toolFactory = new OO.ui.ToolFactory();
7580 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7581 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7583 * // We will be placing status text in this element when tools are used
7584 * var $area = $( '<p>' ).text( 'Toolbar example' );
7586 * // Define the tools that we're going to place in our toolbar
7588 * // Create a class inheriting from OO.ui.Tool
7589 * function PictureTool() {
7590 * PictureTool.parent.apply( this, arguments );
7592 * OO.inheritClass( PictureTool, OO.ui.Tool );
7593 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7594 * // of 'icon' and 'title' (displayed icon and text).
7595 * PictureTool.static.name = 'picture';
7596 * PictureTool.static.icon = 'picture';
7597 * PictureTool.static.title = 'Insert picture';
7598 * // Defines the action that will happen when this tool is selected (clicked).
7599 * PictureTool.prototype.onSelect = function () {
7600 * $area.text( 'Picture tool clicked!' );
7601 * // Never display this tool as "active" (selected).
7602 * this.setActive( false );
7604 * // The toolbar can be synchronized with the state of some external stuff, like a text
7605 * // editor's editing area, highlighting the tools (e.g. a 'bold' tool would be shown as active
7606 * // when the text cursor was inside bolded text). Here we simply disable this feature.
7607 * PictureTool.prototype.onUpdateState = function () {
7609 * // Make this tool available in our toolFactory and thus our toolbar
7610 * toolFactory.register( PictureTool );
7612 * // Register two more tools, nothing interesting here
7613 * function SettingsTool() {
7614 * SettingsTool.parent.apply( this, arguments );
7615 * this.reallyActive = false;
7617 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7618 * SettingsTool.static.name = 'settings';
7619 * SettingsTool.static.icon = 'settings';
7620 * SettingsTool.static.title = 'Change settings';
7621 * SettingsTool.prototype.onSelect = function () {
7622 * $area.text( 'Settings tool clicked!' );
7623 * // Toggle the active state on each click
7624 * this.reallyActive = !this.reallyActive;
7625 * this.setActive( this.reallyActive );
7626 * // To update the menu label
7627 * this.toolbar.emit( 'updateState' );
7629 * SettingsTool.prototype.onUpdateState = function () {
7631 * toolFactory.register( SettingsTool );
7633 * // Register two more tools, nothing interesting here
7634 * function StuffTool() {
7635 * StuffTool.parent.apply( this, arguments );
7636 * this.reallyActive = false;
7638 * OO.inheritClass( StuffTool, OO.ui.Tool );
7639 * StuffTool.static.name = 'stuff';
7640 * StuffTool.static.icon = 'ellipsis';
7641 * StuffTool.static.title = 'More stuff';
7642 * StuffTool.prototype.onSelect = function () {
7643 * $area.text( 'More stuff tool clicked!' );
7644 * // Toggle the active state on each click
7645 * this.reallyActive = !this.reallyActive;
7646 * this.setActive( this.reallyActive );
7647 * // To update the menu label
7648 * this.toolbar.emit( 'updateState' );
7650 * StuffTool.prototype.onUpdateState = function () {
7652 * toolFactory.register( StuffTool );
7654 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7655 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
7656 * function HelpTool( toolGroup, config ) {
7657 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7662 * this.popup.$body.append( '<p>I am helpful!</p>' );
7664 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7665 * HelpTool.static.name = 'help';
7666 * HelpTool.static.icon = 'help';
7667 * HelpTool.static.title = 'Help';
7668 * toolFactory.register( HelpTool );
7670 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7671 * // used once (but not all defined tools must be used).
7674 * // 'bar' tool groups display tools' icons only, side-by-side.
7676 * include: [ 'picture', 'help' ]
7679 * // 'menu' tool groups display both the titles and icons, in a dropdown menu.
7680 * // Menu label indicates which items are selected.
7682 * indicator: 'down',
7683 * include: [ 'settings', 'stuff' ]
7687 * // Create some UI around the toolbar and place it in the document
7688 * var frame = new OO.ui.PanelLayout( {
7692 * var contentFrame = new OO.ui.PanelLayout( {
7696 * frame.$element.append(
7698 * contentFrame.$element.append( $area )
7700 * $( 'body' ).append( frame.$element );
7702 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7704 * toolbar.initialize();
7705 * toolbar.emit( 'updateState' );
7708 * @extends OO.ui.Element
7709 * @mixins OO.EventEmitter
7710 * @mixins OO.ui.mixin.GroupElement
7713 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
7714 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups
7715 * @param {Object} [config] Configuration options
7716 * @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are included
7717 * in the toolbar, but are not configured as tools. By default, actions are displayed on the right side of
7719 * @cfg {boolean} [shadow] Add a shadow below the toolbar.
7721 OO
.ui
.Toolbar
= function OoUiToolbar( toolFactory
, toolGroupFactory
, config
) {
7722 // Allow passing positional parameters inside the config object
7723 if ( OO
.isPlainObject( toolFactory
) && config
=== undefined ) {
7724 config
= toolFactory
;
7725 toolFactory
= config
.toolFactory
;
7726 toolGroupFactory
= config
.toolGroupFactory
;
7729 // Configuration initialization
7730 config
= config
|| {};
7732 // Parent constructor
7733 OO
.ui
.Toolbar
.parent
.call( this, config
);
7735 // Mixin constructors
7736 OO
.EventEmitter
.call( this );
7737 OO
.ui
.mixin
.GroupElement
.call( this, config
);
7740 this.toolFactory
= toolFactory
;
7741 this.toolGroupFactory
= toolGroupFactory
;
7744 this.$bar
= $( '<div>' );
7745 this.$actions
= $( '<div>' );
7746 this.initialized
= false;
7747 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
7751 .add( this.$bar
).add( this.$group
).add( this.$actions
)
7752 .on( 'mousedown keydown', this.onPointerDown
.bind( this ) );
7755 this.$group
.addClass( 'oo-ui-toolbar-tools' );
7756 if ( config
.actions
) {
7757 this.$bar
.append( this.$actions
.addClass( 'oo-ui-toolbar-actions' ) );
7760 .addClass( 'oo-ui-toolbar-bar' )
7761 .append( this.$group
, '<div style="clear:both"></div>' );
7762 if ( config
.shadow
) {
7763 this.$bar
.append( '<div class="oo-ui-toolbar-shadow"></div>' );
7765 this.$element
.addClass( 'oo-ui-toolbar' ).append( this.$bar
);
7770 OO
.inheritClass( OO
.ui
.Toolbar
, OO
.ui
.Element
);
7771 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.EventEmitter
);
7772 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.ui
.mixin
.GroupElement
);
7777 * Get the tool factory.
7779 * @return {OO.ui.ToolFactory} Tool factory
7781 OO
.ui
.Toolbar
.prototype.getToolFactory = function () {
7782 return this.toolFactory
;
7786 * Get the toolgroup factory.
7788 * @return {OO.Factory} Toolgroup factory
7790 OO
.ui
.Toolbar
.prototype.getToolGroupFactory = function () {
7791 return this.toolGroupFactory
;
7795 * Handles mouse down events.
7798 * @param {jQuery.Event} e Mouse down event
7800 OO
.ui
.Toolbar
.prototype.onPointerDown = function ( e
) {
7801 var $closestWidgetToEvent
= $( e
.target
).closest( '.oo-ui-widget' ),
7802 $closestWidgetToToolbar
= this.$element
.closest( '.oo-ui-widget' );
7803 if ( !$closestWidgetToEvent
.length
|| $closestWidgetToEvent
[ 0 ] === $closestWidgetToToolbar
[ 0 ] ) {
7809 * Handle window resize event.
7812 * @param {jQuery.Event} e Window resize event
7814 OO
.ui
.Toolbar
.prototype.onWindowResize = function () {
7815 this.$element
.toggleClass(
7816 'oo-ui-toolbar-narrow',
7817 this.$bar
.width() <= this.narrowThreshold
7822 * Sets up handles and preloads required information for the toolbar to work.
7823 * This must be called after it is attached to a visible document and before doing anything else.
7825 OO
.ui
.Toolbar
.prototype.initialize = function () {
7826 if ( !this.initialized
) {
7827 this.initialized
= true;
7828 this.narrowThreshold
= this.$group
.width() + this.$actions
.width();
7829 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
7830 this.onWindowResize();
7835 * Set up the toolbar.
7837 * The toolbar is set up with a list of toolgroup configurations that specify the type of
7838 * toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or {@link OO.ui.ListToolGroup list})
7839 * to add and which tools to include, exclude, promote, or demote within that toolgroup. Please
7840 * see {@link OO.ui.ToolGroup toolgroups} for more information about including tools in toolgroups.
7842 * @param {Object.<string,Array>} groups List of toolgroup configurations
7843 * @param {Array|string} [groups.include] Tools to include in the toolgroup
7844 * @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup
7845 * @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup
7846 * @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup
7848 OO
.ui
.Toolbar
.prototype.setup = function ( groups
) {
7849 var i
, len
, type
, group
,
7851 defaultType
= 'bar';
7853 // Cleanup previous groups
7856 // Build out new groups
7857 for ( i
= 0, len
= groups
.length
; i
< len
; i
++ ) {
7858 group
= groups
[ i
];
7859 if ( group
.include
=== '*' ) {
7860 // Apply defaults to catch-all groups
7861 if ( group
.type
=== undefined ) {
7862 group
.type
= 'list';
7864 if ( group
.label
=== undefined ) {
7865 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
7868 // Check type has been registered
7869 type
= this.getToolGroupFactory().lookup( group
.type
) ? group
.type
: defaultType
;
7871 this.getToolGroupFactory().create( type
, this, group
)
7874 this.addItems( items
);
7878 * Remove all tools and toolgroups from the toolbar.
7880 OO
.ui
.Toolbar
.prototype.reset = function () {
7885 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
7886 this.items
[ i
].destroy();
7892 * Destroy the toolbar.
7894 * Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. Call
7895 * this method whenever you are done using a toolbar.
7897 OO
.ui
.Toolbar
.prototype.destroy = function () {
7898 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
7900 this.$element
.remove();
7904 * Check if the tool is available.
7906 * Available tools are ones that have not yet been added to the toolbar.
7908 * @param {string} name Symbolic name of tool
7909 * @return {boolean} Tool is available
7911 OO
.ui
.Toolbar
.prototype.isToolAvailable = function ( name
) {
7912 return !this.tools
[ name
];
7916 * Prevent tool from being used again.
7918 * @param {OO.ui.Tool} tool Tool to reserve
7920 OO
.ui
.Toolbar
.prototype.reserveTool = function ( tool
) {
7921 this.tools
[ tool
.getName() ] = tool
;
7925 * Allow tool to be used again.
7927 * @param {OO.ui.Tool} tool Tool to release
7929 OO
.ui
.Toolbar
.prototype.releaseTool = function ( tool
) {
7930 delete this.tools
[ tool
.getName() ];
7934 * Get accelerator label for tool.
7936 * The OOjs UI library does not contain an accelerator system, but this is the hook for one. To
7937 * use an accelerator system, subclass the toolbar and override this method, which is meant to return a label
7938 * that describes the accelerator keys for the tool passed (by symbolic name) to the method.
7940 * @param {string} name Symbolic name of tool
7941 * @return {string|undefined} Tool accelerator label if available
7943 OO
.ui
.Toolbar
.prototype.getToolAccelerator = function () {
7948 * ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a {@link OO.ui.Toolbar toolbar}.
7949 * The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or {@link OO.ui.MenuToolGroup menu})
7950 * to which a tool belongs determines how the tool is arranged and displayed in the toolbar. Toolgroups
7951 * themselves are created on demand with a {@link OO.ui.ToolGroupFactory toolgroup factory}.
7953 * Toolgroups can contain individual tools, groups of tools, or all available tools:
7955 * To include an individual tool (or array of individual tools), specify tools by symbolic name:
7957 * include: [ 'tool-name' ] or [ { name: 'tool-name' }]
7959 * To include a group of tools, specify the group name. (The tool's static ‘group’ config is used to assign the tool to a group.)
7961 * include: [ { group: 'group-name' } ]
7963 * To include all tools that are not yet assigned to a toolgroup, use the catch-all selector, an asterisk (*):
7967 * See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in general,
7968 * please see the [OOjs UI documentation on MediaWiki][1].
7970 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7974 * @extends OO.ui.Widget
7975 * @mixins OO.ui.mixin.GroupElement
7978 * @param {OO.ui.Toolbar} toolbar
7979 * @param {Object} [config] Configuration options
7980 * @cfg {Array|string} [include=[]] List of tools to include in the toolgroup.
7981 * @cfg {Array|string} [exclude=[]] List of tools to exclude from the toolgroup.
7982 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning of the toolgroup.
7983 * @cfg {Array|string} [demote=[]] List of tools to demote to the end of the toolgroup.
7984 * This setting is particularly useful when tools have been added to the toolgroup
7985 * en masse (e.g., via the catch-all selector).
7987 OO
.ui
.ToolGroup
= function OoUiToolGroup( toolbar
, config
) {
7988 // Allow passing positional parameters inside the config object
7989 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
7991 toolbar
= config
.toolbar
;
7994 // Configuration initialization
7995 config
= config
|| {};
7997 // Parent constructor
7998 OO
.ui
.ToolGroup
.parent
.call( this, config
);
8000 // Mixin constructors
8001 OO
.ui
.mixin
.GroupElement
.call( this, config
);
8004 this.toolbar
= toolbar
;
8006 this.pressed
= null;
8007 this.autoDisabled
= false;
8008 this.include
= config
.include
|| [];
8009 this.exclude
= config
.exclude
|| [];
8010 this.promote
= config
.promote
|| [];
8011 this.demote
= config
.demote
|| [];
8012 this.onCapturedMouseKeyUpHandler
= this.onCapturedMouseKeyUp
.bind( this );
8016 mousedown
: this.onMouseKeyDown
.bind( this ),
8017 mouseup
: this.onMouseKeyUp
.bind( this ),
8018 keydown
: this.onMouseKeyDown
.bind( this ),
8019 keyup
: this.onMouseKeyUp
.bind( this ),
8020 focus
: this.onMouseOverFocus
.bind( this ),
8021 blur
: this.onMouseOutBlur
.bind( this ),
8022 mouseover
: this.onMouseOverFocus
.bind( this ),
8023 mouseout
: this.onMouseOutBlur
.bind( this )
8025 this.toolbar
.getToolFactory().connect( this, { register
: 'onToolFactoryRegister' } );
8026 this.aggregate( { disable
: 'itemDisable' } );
8027 this.connect( this, { itemDisable
: 'updateDisabled' } );
8030 this.$group
.addClass( 'oo-ui-toolGroup-tools' );
8032 .addClass( 'oo-ui-toolGroup' )
8033 .append( this.$group
);
8039 OO
.inheritClass( OO
.ui
.ToolGroup
, OO
.ui
.Widget
);
8040 OO
.mixinClass( OO
.ui
.ToolGroup
, OO
.ui
.mixin
.GroupElement
);
8048 /* Static Properties */
8051 * Show labels in tooltips.
8055 * @property {boolean}
8057 OO
.ui
.ToolGroup
.static.titleTooltips
= false;
8060 * Show acceleration labels in tooltips.
8062 * Note: The OOjs UI library does not include an accelerator system, but does contain
8063 * a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and
8064 * override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is
8065 * meant to return a label that describes the accelerator keys for a given tool (e.g., 'Ctrl + M').
8069 * @property {boolean}
8071 OO
.ui
.ToolGroup
.static.accelTooltips
= false;
8074 * Automatically disable the toolgroup when all tools are disabled
8078 * @property {boolean}
8080 OO
.ui
.ToolGroup
.static.autoDisable
= true;
8087 OO
.ui
.ToolGroup
.prototype.isDisabled = function () {
8088 return this.autoDisabled
|| OO
.ui
.ToolGroup
.parent
.prototype.isDisabled
.apply( this, arguments
);
8094 OO
.ui
.ToolGroup
.prototype.updateDisabled = function () {
8095 var i
, item
, allDisabled
= true;
8097 if ( this.constructor.static.autoDisable
) {
8098 for ( i
= this.items
.length
- 1; i
>= 0; i
-- ) {
8099 item
= this.items
[ i
];
8100 if ( !item
.isDisabled() ) {
8101 allDisabled
= false;
8105 this.autoDisabled
= allDisabled
;
8107 OO
.ui
.ToolGroup
.parent
.prototype.updateDisabled
.apply( this, arguments
);
8111 * Handle mouse down and key down events.
8114 * @param {jQuery.Event} e Mouse down or key down event
8116 OO
.ui
.ToolGroup
.prototype.onMouseKeyDown = function ( e
) {
8118 !this.isDisabled() &&
8119 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
8121 this.pressed
= this.getTargetTool( e
);
8122 if ( this.pressed
) {
8123 this.pressed
.setActive( true );
8124 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler
);
8125 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler
);
8132 * Handle captured mouse up and key up events.
8135 * @param {Event} e Mouse up or key up event
8137 OO
.ui
.ToolGroup
.prototype.onCapturedMouseKeyUp = function ( e
) {
8138 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler
);
8139 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler
);
8140 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
8141 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
8142 this.onMouseKeyUp( e
);
8146 * Handle mouse up and key up events.
8149 * @param {jQuery.Event} e Mouse up or key up event
8151 OO
.ui
.ToolGroup
.prototype.onMouseKeyUp = function ( e
) {
8152 var tool
= this.getTargetTool( e
);
8155 !this.isDisabled() && this.pressed
&& this.pressed
=== tool
&&
8156 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
8158 this.pressed
.onSelect();
8159 this.pressed
= null;
8163 this.pressed
= null;
8167 * Handle mouse over and focus events.
8170 * @param {jQuery.Event} e Mouse over or focus event
8172 OO
.ui
.ToolGroup
.prototype.onMouseOverFocus = function ( e
) {
8173 var tool
= this.getTargetTool( e
);
8175 if ( this.pressed
&& this.pressed
=== tool
) {
8176 this.pressed
.setActive( true );
8181 * Handle mouse out and blur events.
8184 * @param {jQuery.Event} e Mouse out or blur event
8186 OO
.ui
.ToolGroup
.prototype.onMouseOutBlur = function ( e
) {
8187 var tool
= this.getTargetTool( e
);
8189 if ( this.pressed
&& this.pressed
=== tool
) {
8190 this.pressed
.setActive( false );
8195 * Get the closest tool to a jQuery.Event.
8197 * Only tool links are considered, which prevents other elements in the tool such as popups from
8198 * triggering tool group interactions.
8201 * @param {jQuery.Event} e
8202 * @return {OO.ui.Tool|null} Tool, `null` if none was found
8204 OO
.ui
.ToolGroup
.prototype.getTargetTool = function ( e
) {
8206 $item
= $( e
.target
).closest( '.oo-ui-tool-link' );
8208 if ( $item
.length
) {
8209 tool
= $item
.parent().data( 'oo-ui-tool' );
8212 return tool
&& !tool
.isDisabled() ? tool
: null;
8216 * Handle tool registry register events.
8218 * If a tool is registered after the group is created, we must repopulate the list to account for:
8220 * - a tool being added that may be included
8221 * - a tool already included being overridden
8224 * @param {string} name Symbolic name of tool
8226 OO
.ui
.ToolGroup
.prototype.onToolFactoryRegister = function () {
8231 * Get the toolbar that contains the toolgroup.
8233 * @return {OO.ui.Toolbar} Toolbar that contains the toolgroup
8235 OO
.ui
.ToolGroup
.prototype.getToolbar = function () {
8236 return this.toolbar
;
8240 * Add and remove tools based on configuration.
8242 OO
.ui
.ToolGroup
.prototype.populate = function () {
8243 var i
, len
, name
, tool
,
8244 toolFactory
= this.toolbar
.getToolFactory(),
8248 list
= this.toolbar
.getToolFactory().getTools(
8249 this.include
, this.exclude
, this.promote
, this.demote
8252 // Build a list of needed tools
8253 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
8257 toolFactory
.lookup( name
) &&
8258 // Tool is available or is already in this group
8259 ( this.toolbar
.isToolAvailable( name
) || this.tools
[ name
] )
8261 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
8262 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
8263 this.toolbar
.tools
[ name
] = true;
8264 tool
= this.tools
[ name
];
8266 // Auto-initialize tools on first use
8267 this.tools
[ name
] = tool
= toolFactory
.create( name
, this );
8270 this.toolbar
.reserveTool( tool
);
8272 names
[ name
] = true;
8275 // Remove tools that are no longer needed
8276 for ( name
in this.tools
) {
8277 if ( !names
[ name
] ) {
8278 this.tools
[ name
].destroy();
8279 this.toolbar
.releaseTool( this.tools
[ name
] );
8280 remove
.push( this.tools
[ name
] );
8281 delete this.tools
[ name
];
8284 if ( remove
.length
) {
8285 this.removeItems( remove
);
8287 // Update emptiness state
8289 this.$element
.removeClass( 'oo-ui-toolGroup-empty' );
8291 this.$element
.addClass( 'oo-ui-toolGroup-empty' );
8293 // Re-add tools (moving existing ones to new locations)
8294 this.addItems( add
);
8295 // Disabled state may depend on items
8296 this.updateDisabled();
8300 * Destroy toolgroup.
8302 OO
.ui
.ToolGroup
.prototype.destroy = function () {
8306 this.toolbar
.getToolFactory().disconnect( this );
8307 for ( name
in this.tools
) {
8308 this.toolbar
.releaseTool( this.tools
[ name
] );
8309 this.tools
[ name
].disconnect( this ).destroy();
8310 delete this.tools
[ name
];
8312 this.$element
.remove();
8316 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
8317 * consists of a header that contains the dialog title, a body with the message, and a footer that
8318 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
8319 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
8321 * There are two basic types of message dialogs, confirmation and alert:
8323 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
8324 * more details about the consequences.
8325 * - **alert**: the dialog title describes which event occurred and the message provides more information
8326 * about why the event occurred.
8328 * The MessageDialog class specifies two actions: ‘accept’, the primary
8329 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
8330 * passing along the selected action.
8332 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
8335 * // Example: Creating and opening a message dialog window.
8336 * var messageDialog = new OO.ui.MessageDialog();
8338 * // Create and append a window manager.
8339 * var windowManager = new OO.ui.WindowManager();
8340 * $( 'body' ).append( windowManager.$element );
8341 * windowManager.addWindows( [ messageDialog ] );
8342 * // Open the window.
8343 * windowManager.openWindow( messageDialog, {
8344 * title: 'Basic message dialog',
8345 * message: 'This is the message'
8348 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
8351 * @extends OO.ui.Dialog
8354 * @param {Object} [config] Configuration options
8356 OO
.ui
.MessageDialog
= function OoUiMessageDialog( config
) {
8357 // Parent constructor
8358 OO
.ui
.MessageDialog
.parent
.call( this, config
);
8361 this.verticalActionLayout
= null;
8364 this.$element
.addClass( 'oo-ui-messageDialog' );
8369 OO
.inheritClass( OO
.ui
.MessageDialog
, OO
.ui
.Dialog
);
8371 /* Static Properties */
8373 OO
.ui
.MessageDialog
.static.name
= 'message';
8375 OO
.ui
.MessageDialog
.static.size
= 'small';
8377 OO
.ui
.MessageDialog
.static.verbose
= false;
8382 * The title of a confirmation dialog describes what a progressive action will do. The
8383 * title of an alert dialog describes which event occurred.
8387 * @property {jQuery|string|Function|null}
8389 OO
.ui
.MessageDialog
.static.title
= null;
8392 * The message displayed in the dialog body.
8394 * A confirmation message describes the consequences of a progressive action. An alert
8395 * message describes why an event occurred.
8399 * @property {jQuery|string|Function|null}
8401 OO
.ui
.MessageDialog
.static.message
= null;
8403 OO
.ui
.MessageDialog
.static.actions
= [
8404 { action
: 'accept', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-accept' ), flags
: 'primary' },
8405 { action
: 'reject', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-reject' ), flags
: 'safe' }
8413 OO
.ui
.MessageDialog
.prototype.setManager = function ( manager
) {
8414 OO
.ui
.MessageDialog
.parent
.prototype.setManager
.call( this, manager
);
8417 this.manager
.connect( this, {
8427 OO
.ui
.MessageDialog
.prototype.onActionResize = function ( action
) {
8429 return OO
.ui
.MessageDialog
.parent
.prototype.onActionResize
.call( this, action
);
8433 * Handle window resized events.
8437 OO
.ui
.MessageDialog
.prototype.onResize = function () {
8439 dialog
.fitActions();
8440 // Wait for CSS transition to finish and do it again :(
8441 setTimeout( function () {
8442 dialog
.fitActions();
8447 * Toggle action layout between vertical and horizontal.
8450 * @param {boolean} [value] Layout actions vertically, omit to toggle
8453 OO
.ui
.MessageDialog
.prototype.toggleVerticalActionLayout = function ( value
) {
8454 value
= value
=== undefined ? !this.verticalActionLayout
: !!value
;
8456 if ( value
!== this.verticalActionLayout
) {
8457 this.verticalActionLayout
= value
;
8459 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value
)
8460 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value
);
8469 OO
.ui
.MessageDialog
.prototype.getActionProcess = function ( action
) {
8471 return new OO
.ui
.Process( function () {
8472 this.close( { action
: action
} );
8475 return OO
.ui
.MessageDialog
.parent
.prototype.getActionProcess
.call( this, action
);
8481 * @param {Object} [data] Dialog opening data
8482 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
8483 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
8484 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
8485 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
8488 OO
.ui
.MessageDialog
.prototype.getSetupProcess = function ( data
) {
8492 return OO
.ui
.MessageDialog
.parent
.prototype.getSetupProcess
.call( this, data
)
8493 .next( function () {
8494 this.title
.setLabel(
8495 data
.title
!== undefined ? data
.title
: this.constructor.static.title
8497 this.message
.setLabel(
8498 data
.message
!== undefined ? data
.message
: this.constructor.static.message
8500 this.message
.$element
.toggleClass(
8501 'oo-ui-messageDialog-message-verbose',
8502 data
.verbose
!== undefined ? data
.verbose
: this.constructor.static.verbose
8510 OO
.ui
.MessageDialog
.prototype.getReadyProcess = function ( data
) {
8514 return OO
.ui
.MessageDialog
.parent
.prototype.getReadyProcess
.call( this, data
)
8515 .next( function () {
8516 // Focus the primary action button
8517 var actions
= this.actions
.get();
8518 actions
= actions
.filter( function ( action
) {
8519 return action
.getFlags().indexOf( 'primary' ) > -1;
8521 if ( actions
.length
> 0 ) {
8522 actions
[ 0 ].$button
.focus();
8530 OO
.ui
.MessageDialog
.prototype.getBodyHeight = function () {
8531 var bodyHeight
, oldOverflow
,
8532 $scrollable
= this.container
.$element
;
8534 oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
8535 $scrollable
[ 0 ].style
.overflow
= 'hidden';
8537 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
8539 bodyHeight
= this.text
.$element
.outerHeight( true );
8540 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
8548 OO
.ui
.MessageDialog
.prototype.setDimensions = function ( dim
) {
8549 var $scrollable
= this.container
.$element
;
8550 OO
.ui
.MessageDialog
.parent
.prototype.setDimensions
.call( this, dim
);
8552 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
8553 // Need to do it after transition completes (250ms), add 50ms just in case.
8554 setTimeout( function () {
8555 var oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
8556 $scrollable
[ 0 ].style
.overflow
= 'hidden';
8558 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
8560 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
8569 OO
.ui
.MessageDialog
.prototype.initialize = function () {
8571 OO
.ui
.MessageDialog
.parent
.prototype.initialize
.call( this );
8574 this.$actions
= $( '<div>' );
8575 this.container
= new OO
.ui
.PanelLayout( {
8576 scrollable
: true, classes
: [ 'oo-ui-messageDialog-container' ]
8578 this.text
= new OO
.ui
.PanelLayout( {
8579 padded
: true, expanded
: false, classes
: [ 'oo-ui-messageDialog-text' ]
8581 this.message
= new OO
.ui
.LabelWidget( {
8582 classes
: [ 'oo-ui-messageDialog-message' ]
8586 this.title
.$element
.addClass( 'oo-ui-messageDialog-title' );
8587 this.$content
.addClass( 'oo-ui-messageDialog-content' );
8588 this.container
.$element
.append( this.text
.$element
);
8589 this.text
.$element
.append( this.title
.$element
, this.message
.$element
);
8590 this.$body
.append( this.container
.$element
);
8591 this.$actions
.addClass( 'oo-ui-messageDialog-actions' );
8592 this.$foot
.append( this.$actions
);
8598 OO
.ui
.MessageDialog
.prototype.attachActions = function () {
8599 var i
, len
, other
, special
, others
;
8602 OO
.ui
.MessageDialog
.parent
.prototype.attachActions
.call( this );
8604 special
= this.actions
.getSpecial();
8605 others
= this.actions
.getOthers();
8607 if ( special
.safe
) {
8608 this.$actions
.append( special
.safe
.$element
);
8609 special
.safe
.toggleFramed( false );
8611 if ( others
.length
) {
8612 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
8613 other
= others
[ i
];
8614 this.$actions
.append( other
.$element
);
8615 other
.toggleFramed( false );
8618 if ( special
.primary
) {
8619 this.$actions
.append( special
.primary
.$element
);
8620 special
.primary
.toggleFramed( false );
8623 if ( !this.isOpening() ) {
8624 // If the dialog is currently opening, this will be called automatically soon.
8625 // This also calls #fitActions.
8631 * Fit action actions into columns or rows.
8633 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
8637 OO
.ui
.MessageDialog
.prototype.fitActions = function () {
8639 previous
= this.verticalActionLayout
,
8640 actions
= this.actions
.get();
8643 this.toggleVerticalActionLayout( false );
8644 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
8645 action
= actions
[ i
];
8646 if ( action
.$element
.innerWidth() < action
.$label
.outerWidth( true ) ) {
8647 this.toggleVerticalActionLayout( true );
8652 // Move the body out of the way of the foot
8653 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
8655 if ( this.verticalActionLayout
!== previous
) {
8656 // We changed the layout, window height might need to be updated.
8662 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
8663 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
8664 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
8665 * relevant. The ProcessDialog class is always extended and customized with the actions and content
8666 * required for each process.
8668 * The process dialog box consists of a header that visually represents the ‘working’ state of long
8669 * processes with an animation. The header contains the dialog title as well as
8670 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
8671 * a ‘primary’ action on the right (e.g., ‘Done’).
8673 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
8674 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
8677 * // Example: Creating and opening a process dialog window.
8678 * function MyProcessDialog( config ) {
8679 * MyProcessDialog.parent.call( this, config );
8681 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
8683 * MyProcessDialog.static.title = 'Process dialog';
8684 * MyProcessDialog.static.actions = [
8685 * { action: 'save', label: 'Done', flags: 'primary' },
8686 * { label: 'Cancel', flags: 'safe' }
8689 * MyProcessDialog.prototype.initialize = function () {
8690 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
8691 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
8692 * 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>' );
8693 * this.$body.append( this.content.$element );
8695 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
8696 * var dialog = this;
8698 * return new OO.ui.Process( function () {
8699 * dialog.close( { action: action } );
8702 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
8705 * var windowManager = new OO.ui.WindowManager();
8706 * $( 'body' ).append( windowManager.$element );
8708 * var dialog = new MyProcessDialog();
8709 * windowManager.addWindows( [ dialog ] );
8710 * windowManager.openWindow( dialog );
8712 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
8716 * @extends OO.ui.Dialog
8719 * @param {Object} [config] Configuration options
8721 OO
.ui
.ProcessDialog
= function OoUiProcessDialog( config
) {
8722 // Parent constructor
8723 OO
.ui
.ProcessDialog
.parent
.call( this, config
);
8726 this.fitOnOpen
= false;
8729 this.$element
.addClass( 'oo-ui-processDialog' );
8734 OO
.inheritClass( OO
.ui
.ProcessDialog
, OO
.ui
.Dialog
);
8739 * Handle dismiss button click events.
8745 OO
.ui
.ProcessDialog
.prototype.onDismissErrorButtonClick = function () {
8750 * Handle retry button click events.
8752 * Hides errors and then tries again.
8756 OO
.ui
.ProcessDialog
.prototype.onRetryButtonClick = function () {
8758 this.executeAction( this.currentAction
);
8764 OO
.ui
.ProcessDialog
.prototype.onActionResize = function ( action
) {
8765 if ( this.actions
.isSpecial( action
) ) {
8768 return OO
.ui
.ProcessDialog
.parent
.prototype.onActionResize
.call( this, action
);
8774 OO
.ui
.ProcessDialog
.prototype.initialize = function () {
8776 OO
.ui
.ProcessDialog
.parent
.prototype.initialize
.call( this );
8779 this.$navigation
= $( '<div>' );
8780 this.$location
= $( '<div>' );
8781 this.$safeActions
= $( '<div>' );
8782 this.$primaryActions
= $( '<div>' );
8783 this.$otherActions
= $( '<div>' );
8784 this.dismissButton
= new OO
.ui
.ButtonWidget( {
8785 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' )
8787 this.retryButton
= new OO
.ui
.ButtonWidget();
8788 this.$errors
= $( '<div>' );
8789 this.$errorsTitle
= $( '<div>' );
8792 this.dismissButton
.connect( this, { click
: 'onDismissErrorButtonClick' } );
8793 this.retryButton
.connect( this, { click
: 'onRetryButtonClick' } );
8796 this.title
.$element
.addClass( 'oo-ui-processDialog-title' );
8798 .append( this.title
.$element
)
8799 .addClass( 'oo-ui-processDialog-location' );
8800 this.$safeActions
.addClass( 'oo-ui-processDialog-actions-safe' );
8801 this.$primaryActions
.addClass( 'oo-ui-processDialog-actions-primary' );
8802 this.$otherActions
.addClass( 'oo-ui-processDialog-actions-other' );
8804 .addClass( 'oo-ui-processDialog-errors-title' )
8805 .text( OO
.ui
.msg( 'ooui-dialog-process-error' ) );
8807 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
8808 .append( this.$errorsTitle
, this.dismissButton
.$element
, this.retryButton
.$element
);
8810 .addClass( 'oo-ui-processDialog-content' )
8811 .append( this.$errors
);
8813 .addClass( 'oo-ui-processDialog-navigation' )
8814 .append( this.$safeActions
, this.$location
, this.$primaryActions
);
8815 this.$head
.append( this.$navigation
);
8816 this.$foot
.append( this.$otherActions
);
8822 OO
.ui
.ProcessDialog
.prototype.getActionWidgets = function ( actions
) {
8823 var i
, len
, widgets
= [];
8824 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
8826 new OO
.ui
.ActionWidget( $.extend( { framed
: true }, actions
[ i
] ) )
8835 OO
.ui
.ProcessDialog
.prototype.attachActions = function () {
8836 var i
, len
, other
, special
, others
;
8839 OO
.ui
.ProcessDialog
.parent
.prototype.attachActions
.call( this );
8841 special
= this.actions
.getSpecial();
8842 others
= this.actions
.getOthers();
8843 if ( special
.primary
) {
8844 this.$primaryActions
.append( special
.primary
.$element
);
8846 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
8847 other
= others
[ i
];
8848 this.$otherActions
.append( other
.$element
);
8850 if ( special
.safe
) {
8851 this.$safeActions
.append( special
.safe
.$element
);
8855 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
8861 OO
.ui
.ProcessDialog
.prototype.executeAction = function ( action
) {
8863 return OO
.ui
.ProcessDialog
.parent
.prototype.executeAction
.call( this, action
)
8864 .fail( function ( errors
) {
8865 process
.showErrors( errors
|| [] );
8872 OO
.ui
.ProcessDialog
.prototype.setDimensions = function () {
8874 OO
.ui
.ProcessDialog
.parent
.prototype.setDimensions
.apply( this, arguments
);
8880 * Fit label between actions.
8885 OO
.ui
.ProcessDialog
.prototype.fitLabel = function () {
8886 var safeWidth
, primaryWidth
, biggerWidth
, labelWidth
, navigationWidth
, leftWidth
, rightWidth
,
8887 size
= this.getSizeProperties();
8889 if ( typeof size
.width
!== 'number' ) {
8890 if ( this.isOpened() ) {
8891 navigationWidth
= this.$head
.width() - 20;
8892 } else if ( this.isOpening() ) {
8893 if ( !this.fitOnOpen
) {
8894 // Size is relative and the dialog isn't open yet, so wait.
8895 this.manager
.opening
.done( this.fitLabel
.bind( this ) );
8896 this.fitOnOpen
= true;
8903 navigationWidth
= size
.width
- 20;
8906 safeWidth
= this.$safeActions
.is( ':visible' ) ? this.$safeActions
.width() : 0;
8907 primaryWidth
= this.$primaryActions
.is( ':visible' ) ? this.$primaryActions
.width() : 0;
8908 biggerWidth
= Math
.max( safeWidth
, primaryWidth
);
8910 labelWidth
= this.title
.$element
.width();
8912 if ( 2 * biggerWidth
+ labelWidth
< navigationWidth
) {
8913 // We have enough space to center the label
8914 leftWidth
= rightWidth
= biggerWidth
;
8916 // Let's hope we at least have enough space not to overlap, because we can't wrap the label…
8917 if ( this.getDir() === 'ltr' ) {
8918 leftWidth
= safeWidth
;
8919 rightWidth
= primaryWidth
;
8921 leftWidth
= primaryWidth
;
8922 rightWidth
= safeWidth
;
8926 this.$location
.css( { paddingLeft
: leftWidth
, paddingRight
: rightWidth
} );
8932 * Handle errors that occurred during accept or reject processes.
8935 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
8937 OO
.ui
.ProcessDialog
.prototype.showErrors = function ( errors
) {
8938 var i
, len
, $item
, actions
,
8944 if ( errors
instanceof OO
.ui
.Error
) {
8945 errors
= [ errors
];
8948 for ( i
= 0, len
= errors
.length
; i
< len
; i
++ ) {
8949 if ( !errors
[ i
].isRecoverable() ) {
8950 recoverable
= false;
8952 if ( errors
[ i
].isWarning() ) {
8955 $item
= $( '<div>' )
8956 .addClass( 'oo-ui-processDialog-error' )
8957 .append( errors
[ i
].getMessage() );
8958 items
.push( $item
[ 0 ] );
8960 this.$errorItems
= $( items
);
8961 if ( recoverable
) {
8962 abilities
[ this.currentAction
] = true;
8963 // Copy the flags from the first matching action
8964 actions
= this.actions
.get( { actions
: this.currentAction
} );
8965 if ( actions
.length
) {
8966 this.retryButton
.clearFlags().setFlags( actions
[ 0 ].getFlags() );
8969 abilities
[ this.currentAction
] = false;
8970 this.actions
.setAbilities( abilities
);
8973 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-continue' ) );
8975 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-retry' ) );
8977 this.retryButton
.toggle( recoverable
);
8978 this.$errorsTitle
.after( this.$errorItems
);
8979 this.$errors
.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
8987 OO
.ui
.ProcessDialog
.prototype.hideErrors = function () {
8988 this.$errors
.addClass( 'oo-ui-element-hidden' );
8989 if ( this.$errorItems
) {
8990 this.$errorItems
.remove();
8991 this.$errorItems
= null;
8998 OO
.ui
.ProcessDialog
.prototype.getTeardownProcess = function ( data
) {
9000 return OO
.ui
.ProcessDialog
.parent
.prototype.getTeardownProcess
.call( this, data
)
9001 .first( function () {
9002 // Make sure to hide errors
9004 this.fitOnOpen
= false;
9009 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
9010 * which is a widget that is specified by reference before any optional configuration settings.
9012 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
9014 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9015 * A left-alignment is used for forms with many fields.
9016 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9017 * A right-alignment is used for long but familiar forms which users tab through,
9018 * verifying the current field with a quick glance at the label.
9019 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9020 * that users fill out from top to bottom.
9021 * - **inline**: The label is placed after the field-widget and aligned to the left.
9022 * An inline-alignment is best used with checkboxes or radio buttons.
9024 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
9025 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
9027 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9029 * @extends OO.ui.Layout
9030 * @mixins OO.ui.mixin.LabelElement
9031 * @mixins OO.ui.mixin.TitledElement
9034 * @param {OO.ui.Widget} fieldWidget Field widget
9035 * @param {Object} [config] Configuration options
9036 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
9037 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
9038 * The array may contain strings or OO.ui.HtmlSnippet instances.
9039 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
9040 * The array may contain strings or OO.ui.HtmlSnippet instances.
9041 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
9042 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
9043 * For important messages, you are advised to use `notices`, as they are always shown.
9045 * @throws {Error} An error is thrown if no widget is specified
9047 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
9048 var hasInputWidget
, div
;
9050 // Allow passing positional parameters inside the config object
9051 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
9052 config
= fieldWidget
;
9053 fieldWidget
= config
.fieldWidget
;
9056 // Make sure we have required constructor arguments
9057 if ( fieldWidget
=== undefined ) {
9058 throw new Error( 'Widget not found' );
9061 hasInputWidget
= fieldWidget
.constructor.static.supportsSimpleLabel
;
9063 // Configuration initialization
9064 config
= $.extend( { align
: 'left' }, config
);
9066 // Parent constructor
9067 OO
.ui
.FieldLayout
.parent
.call( this, config
);
9069 // Mixin constructors
9070 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9071 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
9074 this.fieldWidget
= fieldWidget
;
9077 this.$field
= $( '<div>' );
9078 this.$messages
= $( '<ul>' );
9079 this.$body
= $( '<' + ( hasInputWidget
? 'label' : 'div' ) + '>' );
9081 if ( config
.help
) {
9082 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
9083 classes
: [ 'oo-ui-fieldLayout-help' ],
9089 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
9090 div
.html( config
.help
.toString() );
9092 div
.text( config
.help
);
9094 this.popupButtonWidget
.getPopup().$body
.append(
9095 div
.addClass( 'oo-ui-fieldLayout-help-content' )
9097 this.$help
= this.popupButtonWidget
.$element
;
9099 this.$help
= $( [] );
9103 if ( hasInputWidget
) {
9104 this.$label
.on( 'click', this.onLabelClick
.bind( this ) );
9106 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
9110 .addClass( 'oo-ui-fieldLayout' )
9111 .append( this.$help
, this.$body
);
9112 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
9113 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
9115 .addClass( 'oo-ui-fieldLayout-field' )
9116 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget
.isDisabled() )
9117 .append( this.fieldWidget
.$element
);
9119 this.setErrors( config
.errors
|| [] );
9120 this.setNotices( config
.notices
|| [] );
9121 this.setAlignment( config
.align
);
9126 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
9127 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
9128 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
9133 * Handle field disable events.
9136 * @param {boolean} value Field is disabled
9138 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
9139 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
9143 * Handle label mouse click events.
9146 * @param {jQuery.Event} e Mouse click event
9148 OO
.ui
.FieldLayout
.prototype.onLabelClick = function () {
9149 this.fieldWidget
.simulateLabelClick();
9154 * Get the widget contained by the field.
9156 * @return {OO.ui.Widget} Field widget
9158 OO
.ui
.FieldLayout
.prototype.getField = function () {
9159 return this.fieldWidget
;
9164 * @param {string} kind 'error' or 'notice'
9165 * @param {string|OO.ui.HtmlSnippet} text
9168 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
9169 var $listItem
, $icon
, message
;
9170 $listItem
= $( '<li>' );
9171 if ( kind
=== 'error' ) {
9172 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
9173 } else if ( kind
=== 'notice' ) {
9174 $icon
= new OO
.ui
.IconWidget( { icon
: 'info' } ).$element
;
9178 message
= new OO
.ui
.LabelWidget( { label
: text
} );
9180 .append( $icon
, message
.$element
)
9181 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
9186 * Set the field alignment mode.
9189 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
9192 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
9193 if ( value
!== this.align
) {
9194 // Default to 'left'
9195 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
9199 if ( value
=== 'inline' ) {
9200 this.$body
.append( this.$field
, this.$label
);
9202 this.$body
.append( this.$label
, this.$field
);
9204 // Set classes. The following classes can be used here:
9205 // * oo-ui-fieldLayout-align-left
9206 // * oo-ui-fieldLayout-align-right
9207 // * oo-ui-fieldLayout-align-top
9208 // * oo-ui-fieldLayout-align-inline
9210 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
9212 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
9220 * Set the list of error messages.
9222 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
9223 * The array may contain strings or OO.ui.HtmlSnippet instances.
9226 OO
.ui
.FieldLayout
.prototype.setErrors = function ( errors
) {
9227 this.errors
= errors
.slice();
9228 this.updateMessages();
9233 * Set the list of notice messages.
9235 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
9236 * The array may contain strings or OO.ui.HtmlSnippet instances.
9239 OO
.ui
.FieldLayout
.prototype.setNotices = function ( notices
) {
9240 this.notices
= notices
.slice();
9241 this.updateMessages();
9246 * Update the rendering of error and notice messages.
9250 OO
.ui
.FieldLayout
.prototype.updateMessages = function () {
9252 this.$messages
.empty();
9254 if ( this.errors
.length
|| this.notices
.length
) {
9255 this.$body
.after( this.$messages
);
9257 this.$messages
.remove();
9261 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
9262 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
9264 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
9265 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
9270 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
9271 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
9272 * is required and is specified before any optional configuration settings.
9274 * Labels can be aligned in one of four ways:
9276 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9277 * A left-alignment is used for forms with many fields.
9278 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9279 * A right-alignment is used for long but familiar forms which users tab through,
9280 * verifying the current field with a quick glance at the label.
9281 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9282 * that users fill out from top to bottom.
9283 * - **inline**: The label is placed after the field-widget and aligned to the left.
9284 * An inline-alignment is best used with checkboxes or radio buttons.
9286 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
9287 * text is specified.
9290 * // Example of an ActionFieldLayout
9291 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
9292 * new OO.ui.TextInputWidget( {
9293 * placeholder: 'Field widget'
9295 * new OO.ui.ButtonWidget( {
9299 * label: 'An ActionFieldLayout. This label is aligned top',
9301 * help: 'This is help text'
9305 * $( 'body' ).append( actionFieldLayout.$element );
9308 * @extends OO.ui.FieldLayout
9311 * @param {OO.ui.Widget} fieldWidget Field widget
9312 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
9314 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
9315 // Allow passing positional parameters inside the config object
9316 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
9317 config
= fieldWidget
;
9318 fieldWidget
= config
.fieldWidget
;
9319 buttonWidget
= config
.buttonWidget
;
9322 // Parent constructor
9323 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
9326 this.buttonWidget
= buttonWidget
;
9327 this.$button
= $( '<div>' );
9328 this.$input
= $( '<div>' );
9332 .addClass( 'oo-ui-actionFieldLayout' );
9334 .addClass( 'oo-ui-actionFieldLayout-button' )
9335 .append( this.buttonWidget
.$element
);
9337 .addClass( 'oo-ui-actionFieldLayout-input' )
9338 .append( this.fieldWidget
.$element
);
9340 .append( this.$input
, this.$button
);
9345 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
9348 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
9349 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
9350 * configured with a label as well. For more information and examples,
9351 * please see the [OOjs UI documentation on MediaWiki][1].
9354 * // Example of a fieldset layout
9355 * var input1 = new OO.ui.TextInputWidget( {
9356 * placeholder: 'A text input field'
9359 * var input2 = new OO.ui.TextInputWidget( {
9360 * placeholder: 'A text input field'
9363 * var fieldset = new OO.ui.FieldsetLayout( {
9364 * label: 'Example of a fieldset layout'
9367 * fieldset.addItems( [
9368 * new OO.ui.FieldLayout( input1, {
9369 * label: 'Field One'
9371 * new OO.ui.FieldLayout( input2, {
9372 * label: 'Field Two'
9375 * $( 'body' ).append( fieldset.$element );
9377 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9380 * @extends OO.ui.Layout
9381 * @mixins OO.ui.mixin.IconElement
9382 * @mixins OO.ui.mixin.LabelElement
9383 * @mixins OO.ui.mixin.GroupElement
9386 * @param {Object} [config] Configuration options
9387 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
9389 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
9390 // Configuration initialization
9391 config
= config
|| {};
9393 // Parent constructor
9394 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
9396 // Mixin constructors
9397 OO
.ui
.mixin
.IconElement
.call( this, config
);
9398 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9399 OO
.ui
.mixin
.GroupElement
.call( this, config
);
9401 if ( config
.help
) {
9402 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
9403 classes
: [ 'oo-ui-fieldsetLayout-help' ],
9408 this.popupButtonWidget
.getPopup().$body
.append(
9410 .text( config
.help
)
9411 .addClass( 'oo-ui-fieldsetLayout-help-content' )
9413 this.$help
= this.popupButtonWidget
.$element
;
9415 this.$help
= $( [] );
9420 .addClass( 'oo-ui-fieldsetLayout' )
9421 .prepend( this.$help
, this.$icon
, this.$label
, this.$group
);
9422 if ( Array
.isArray( config
.items
) ) {
9423 this.addItems( config
.items
);
9429 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
9430 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
9431 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
9432 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
9435 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
9436 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
9437 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
9438 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9440 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
9441 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
9442 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
9443 * some fancier controls. Some controls have both regular and InputWidget variants, for example
9444 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
9445 * often have simplified APIs to match the capabilities of HTML forms.
9446 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
9448 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
9449 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9452 * // Example of a form layout that wraps a fieldset layout
9453 * var input1 = new OO.ui.TextInputWidget( {
9454 * placeholder: 'Username'
9456 * var input2 = new OO.ui.TextInputWidget( {
9457 * placeholder: 'Password',
9460 * var submit = new OO.ui.ButtonInputWidget( {
9464 * var fieldset = new OO.ui.FieldsetLayout( {
9465 * label: 'A form layout'
9467 * fieldset.addItems( [
9468 * new OO.ui.FieldLayout( input1, {
9469 * label: 'Username',
9472 * new OO.ui.FieldLayout( input2, {
9473 * label: 'Password',
9476 * new OO.ui.FieldLayout( submit )
9478 * var form = new OO.ui.FormLayout( {
9479 * items: [ fieldset ],
9480 * action: '/api/formhandler',
9483 * $( 'body' ).append( form.$element );
9486 * @extends OO.ui.Layout
9487 * @mixins OO.ui.mixin.GroupElement
9490 * @param {Object} [config] Configuration options
9491 * @cfg {string} [method] HTML form `method` attribute
9492 * @cfg {string} [action] HTML form `action` attribute
9493 * @cfg {string} [enctype] HTML form `enctype` attribute
9494 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
9496 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
9497 // Configuration initialization
9498 config
= config
|| {};
9500 // Parent constructor
9501 OO
.ui
.FormLayout
.parent
.call( this, config
);
9503 // Mixin constructors
9504 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
9507 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
9509 // Make sure the action is safe
9510 if ( config
.action
!== undefined && !OO
.ui
.isSafeUrl( config
.action
) ) {
9511 throw new Error( 'Potentially unsafe action provided: ' + config
.action
);
9516 .addClass( 'oo-ui-formLayout' )
9518 method
: config
.method
,
9519 action
: config
.action
,
9520 enctype
: config
.enctype
9522 if ( Array
.isArray( config
.items
) ) {
9523 this.addItems( config
.items
);
9529 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
9530 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
9535 * A 'submit' event is emitted when the form is submitted.
9540 /* Static Properties */
9542 OO
.ui
.FormLayout
.static.tagName
= 'form';
9547 * Handle form submit events.
9550 * @param {jQuery.Event} e Submit event
9553 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
9554 if ( this.emit( 'submit' ) ) {
9560 * 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)
9561 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
9564 * var menuLayout = new OO.ui.MenuLayout( {
9567 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9568 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9569 * select = new OO.ui.SelectWidget( {
9571 * new OO.ui.OptionWidget( {
9575 * new OO.ui.OptionWidget( {
9579 * new OO.ui.OptionWidget( {
9583 * new OO.ui.OptionWidget( {
9588 * } ).on( 'select', function ( item ) {
9589 * menuLayout.setMenuPosition( item.getData() );
9592 * menuLayout.$menu.append(
9593 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
9595 * menuLayout.$content.append(
9596 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
9598 * $( 'body' ).append( menuLayout.$element );
9600 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
9601 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
9602 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
9605 * .oo-ui-menuLayout-menu {
9609 * .oo-ui-menuLayout-content {
9617 * @extends OO.ui.Layout
9620 * @param {Object} [config] Configuration options
9621 * @cfg {boolean} [showMenu=true] Show menu
9622 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
9624 OO
.ui
.MenuLayout
= function OoUiMenuLayout( config
) {
9625 // Configuration initialization
9626 config
= $.extend( {
9628 menuPosition
: 'before'
9631 // Parent constructor
9632 OO
.ui
.MenuLayout
.parent
.call( this, config
);
9637 * @property {jQuery}
9639 this.$menu
= $( '<div>' );
9643 * @property {jQuery}
9645 this.$content
= $( '<div>' );
9649 .addClass( 'oo-ui-menuLayout-menu' );
9650 this.$content
.addClass( 'oo-ui-menuLayout-content' );
9652 .addClass( 'oo-ui-menuLayout' )
9653 .append( this.$content
, this.$menu
);
9654 this.setMenuPosition( config
.menuPosition
);
9655 this.toggleMenu( config
.showMenu
);
9660 OO
.inheritClass( OO
.ui
.MenuLayout
, OO
.ui
.Layout
);
9667 * @param {boolean} showMenu Show menu, omit to toggle
9670 OO
.ui
.MenuLayout
.prototype.toggleMenu = function ( showMenu
) {
9671 showMenu
= showMenu
=== undefined ? !this.showMenu
: !!showMenu
;
9673 if ( this.showMenu
!== showMenu
) {
9674 this.showMenu
= showMenu
;
9676 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu
)
9677 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu
);
9684 * Check if menu is visible
9686 * @return {boolean} Menu is visible
9688 OO
.ui
.MenuLayout
.prototype.isMenuVisible = function () {
9689 return this.showMenu
;
9693 * Set menu position.
9695 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
9696 * @throws {Error} If position value is not supported
9699 OO
.ui
.MenuLayout
.prototype.setMenuPosition = function ( position
) {
9700 this.$element
.removeClass( 'oo-ui-menuLayout-' + this.menuPosition
);
9701 this.menuPosition
= position
;
9702 this.$element
.addClass( 'oo-ui-menuLayout-' + position
);
9708 * Get menu position.
9710 * @return {string} Menu position
9712 OO
.ui
.MenuLayout
.prototype.getMenuPosition = function () {
9713 return this.menuPosition
;
9717 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
9718 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
9719 * through the pages and select which one to display. By default, only one page is
9720 * displayed at a time and the outline is hidden. When a user navigates to a new page,
9721 * the booklet layout automatically focuses on the first focusable element, unless the
9722 * default setting is changed. Optionally, booklets can be configured to show
9723 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
9726 * // Example of a BookletLayout that contains two PageLayouts.
9728 * function PageOneLayout( name, config ) {
9729 * PageOneLayout.parent.call( this, name, config );
9730 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
9732 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
9733 * PageOneLayout.prototype.setupOutlineItem = function () {
9734 * this.outlineItem.setLabel( 'Page One' );
9737 * function PageTwoLayout( name, config ) {
9738 * PageTwoLayout.parent.call( this, name, config );
9739 * this.$element.append( '<p>Second page</p>' );
9741 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
9742 * PageTwoLayout.prototype.setupOutlineItem = function () {
9743 * this.outlineItem.setLabel( 'Page Two' );
9746 * var page1 = new PageOneLayout( 'one' ),
9747 * page2 = new PageTwoLayout( 'two' );
9749 * var booklet = new OO.ui.BookletLayout( {
9753 * booklet.addPages ( [ page1, page2 ] );
9754 * $( 'body' ).append( booklet.$element );
9757 * @extends OO.ui.MenuLayout
9760 * @param {Object} [config] Configuration options
9761 * @cfg {boolean} [continuous=false] Show all pages, one after another
9762 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
9763 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
9764 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
9766 OO
.ui
.BookletLayout
= function OoUiBookletLayout( config
) {
9767 // Configuration initialization
9768 config
= config
|| {};
9770 // Parent constructor
9771 OO
.ui
.BookletLayout
.parent
.call( this, config
);
9774 this.currentPageName
= null;
9776 this.ignoreFocus
= false;
9777 this.stackLayout
= new OO
.ui
.StackLayout( { continuous
: !!config
.continuous
} );
9778 this.$content
.append( this.stackLayout
.$element
);
9779 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
9780 this.outlineVisible
= false;
9781 this.outlined
= !!config
.outlined
;
9782 if ( this.outlined
) {
9783 this.editable
= !!config
.editable
;
9784 this.outlineControlsWidget
= null;
9785 this.outlineSelectWidget
= new OO
.ui
.OutlineSelectWidget();
9786 this.outlinePanel
= new OO
.ui
.PanelLayout( { scrollable
: true } );
9787 this.$menu
.append( this.outlinePanel
.$element
);
9788 this.outlineVisible
= true;
9789 if ( this.editable
) {
9790 this.outlineControlsWidget
= new OO
.ui
.OutlineControlsWidget(
9791 this.outlineSelectWidget
9795 this.toggleMenu( this.outlined
);
9798 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
9799 if ( this.outlined
) {
9800 this.outlineSelectWidget
.connect( this, { select
: 'onOutlineSelectWidgetSelect' } );
9801 this.scrolling
= false;
9802 this.stackLayout
.connect( this, { visibleItemChange
: 'onStackLayoutVisibleItemChange' } );
9804 if ( this.autoFocus
) {
9805 // Event 'focus' does not bubble, but 'focusin' does
9806 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
9810 this.$element
.addClass( 'oo-ui-bookletLayout' );
9811 this.stackLayout
.$element
.addClass( 'oo-ui-bookletLayout-stackLayout' );
9812 if ( this.outlined
) {
9813 this.outlinePanel
.$element
9814 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
9815 .append( this.outlineSelectWidget
.$element
);
9816 if ( this.editable
) {
9817 this.outlinePanel
.$element
9818 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
9819 .append( this.outlineControlsWidget
.$element
);
9826 OO
.inheritClass( OO
.ui
.BookletLayout
, OO
.ui
.MenuLayout
);
9831 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
9833 * @param {OO.ui.PageLayout} page Current page
9837 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
9840 * @param {OO.ui.PageLayout[]} page Added pages
9841 * @param {number} index Index pages were added at
9845 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
9846 * {@link #removePages removed} from the booklet.
9849 * @param {OO.ui.PageLayout[]} pages Removed pages
9855 * Handle stack layout focus.
9858 * @param {jQuery.Event} e Focusin event
9860 OO
.ui
.BookletLayout
.prototype.onStackLayoutFocus = function ( e
) {
9863 // Find the page that an element was focused within
9864 $target
= $( e
.target
).closest( '.oo-ui-pageLayout' );
9865 for ( name
in this.pages
) {
9866 // Check for page match, exclude current page to find only page changes
9867 if ( this.pages
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentPageName
) {
9868 this.setPage( name
);
9875 * Handle visibleItemChange events from the stackLayout
9877 * The next visible page is set as the current page by selecting it
9880 * @param {OO.ui.PageLayout} page The next visible page in the layout
9882 OO
.ui
.BookletLayout
.prototype.onStackLayoutVisibleItemChange = function ( page
) {
9883 // Set a flag to so that the resulting call to #onStackLayoutSet doesn't
9884 // try and scroll the item into view again.
9885 this.scrolling
= true;
9886 this.outlineSelectWidget
.selectItemByData( page
.getName() );
9887 this.scrolling
= false;
9891 * Handle stack layout set events.
9894 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
9896 OO
.ui
.BookletLayout
.prototype.onStackLayoutSet = function ( page
) {
9898 if ( !this.scrolling
&& page
) {
9899 page
.scrollElementIntoView( { complete: function () {
9900 if ( layout
.autoFocus
) {
9908 * Focus the first input in the current page.
9910 * If no page is selected, the first selectable page will be selected.
9911 * If the focus is already in an element on the current page, nothing will happen.
9912 * @param {number} [itemIndex] A specific item to focus on
9914 OO
.ui
.BookletLayout
.prototype.focus = function ( itemIndex
) {
9916 items
= this.stackLayout
.getItems();
9918 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
9919 page
= items
[ itemIndex
];
9921 page
= this.stackLayout
.getCurrentItem();
9924 if ( !page
&& this.outlined
) {
9925 this.selectFirstSelectablePage();
9926 page
= this.stackLayout
.getCurrentItem();
9931 // Only change the focus if is not already in the current page
9932 if ( !OO
.ui
.contains( page
.$element
[ 0 ], this.getElementDocument().activeElement
, true ) ) {
9938 * Find the first focusable input in the booklet layout and focus
9941 OO
.ui
.BookletLayout
.prototype.focusFirstFocusable = function () {
9942 OO
.ui
.findFocusable( this.stackLayout
.$element
).focus();
9946 * Handle outline widget select events.
9949 * @param {OO.ui.OptionWidget|null} item Selected item
9951 OO
.ui
.BookletLayout
.prototype.onOutlineSelectWidgetSelect = function ( item
) {
9953 this.setPage( item
.getData() );
9958 * Check if booklet has an outline.
9960 * @return {boolean} Booklet has an outline
9962 OO
.ui
.BookletLayout
.prototype.isOutlined = function () {
9963 return this.outlined
;
9967 * Check if booklet has editing controls.
9969 * @return {boolean} Booklet is editable
9971 OO
.ui
.BookletLayout
.prototype.isEditable = function () {
9972 return this.editable
;
9976 * Check if booklet has a visible outline.
9978 * @return {boolean} Outline is visible
9980 OO
.ui
.BookletLayout
.prototype.isOutlineVisible = function () {
9981 return this.outlined
&& this.outlineVisible
;
9985 * Hide or show the outline.
9987 * @param {boolean} [show] Show outline, omit to invert current state
9990 OO
.ui
.BookletLayout
.prototype.toggleOutline = function ( show
) {
9991 if ( this.outlined
) {
9992 show
= show
=== undefined ? !this.outlineVisible
: !!show
;
9993 this.outlineVisible
= show
;
9994 this.toggleMenu( show
);
10001 * Get the page closest to the specified page.
10003 * @param {OO.ui.PageLayout} page Page to use as a reference point
10004 * @return {OO.ui.PageLayout|null} Page closest to the specified page
10006 OO
.ui
.BookletLayout
.prototype.getClosestPage = function ( page
) {
10007 var next
, prev
, level
,
10008 pages
= this.stackLayout
.getItems(),
10009 index
= pages
.indexOf( page
);
10011 if ( index
!== -1 ) {
10012 next
= pages
[ index
+ 1 ];
10013 prev
= pages
[ index
- 1 ];
10014 // Prefer adjacent pages at the same level
10015 if ( this.outlined
) {
10016 level
= this.outlineSelectWidget
.getItemFromData( page
.getName() ).getLevel();
10019 level
=== this.outlineSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
10025 level
=== this.outlineSelectWidget
.getItemFromData( next
.getName() ).getLevel()
10031 return prev
|| next
|| null;
10035 * Get the outline widget.
10037 * If the booklet is not outlined, the method will return `null`.
10039 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
10041 OO
.ui
.BookletLayout
.prototype.getOutline = function () {
10042 return this.outlineSelectWidget
;
10046 * Get the outline controls widget.
10048 * If the outline is not editable, the method will return `null`.
10050 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
10052 OO
.ui
.BookletLayout
.prototype.getOutlineControls = function () {
10053 return this.outlineControlsWidget
;
10057 * Get a page by its symbolic name.
10059 * @param {string} name Symbolic name of page
10060 * @return {OO.ui.PageLayout|undefined} Page, if found
10062 OO
.ui
.BookletLayout
.prototype.getPage = function ( name
) {
10063 return this.pages
[ name
];
10067 * Get the current page.
10069 * @return {OO.ui.PageLayout|undefined} Current page, if found
10071 OO
.ui
.BookletLayout
.prototype.getCurrentPage = function () {
10072 var name
= this.getCurrentPageName();
10073 return name
? this.getPage( name
) : undefined;
10077 * Get the symbolic name of the current page.
10079 * @return {string|null} Symbolic name of the current page
10081 OO
.ui
.BookletLayout
.prototype.getCurrentPageName = function () {
10082 return this.currentPageName
;
10086 * Add pages to the booklet layout
10088 * When pages are added with the same names as existing pages, the existing pages will be
10089 * automatically removed before the new pages are added.
10091 * @param {OO.ui.PageLayout[]} pages Pages to add
10092 * @param {number} index Index of the insertion point
10096 OO
.ui
.BookletLayout
.prototype.addPages = function ( pages
, index
) {
10097 var i
, len
, name
, page
, item
, currentIndex
,
10098 stackLayoutPages
= this.stackLayout
.getItems(),
10102 // Remove pages with same names
10103 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
10105 name
= page
.getName();
10107 if ( Object
.prototype.hasOwnProperty
.call( this.pages
, name
) ) {
10108 // Correct the insertion index
10109 currentIndex
= stackLayoutPages
.indexOf( this.pages
[ name
] );
10110 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
10113 remove
.push( this.pages
[ name
] );
10116 if ( remove
.length
) {
10117 this.removePages( remove
);
10121 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
10123 name
= page
.getName();
10124 this.pages
[ page
.getName() ] = page
;
10125 if ( this.outlined
) {
10126 item
= new OO
.ui
.OutlineOptionWidget( { data
: name
} );
10127 page
.setOutlineItem( item
);
10128 items
.push( item
);
10132 if ( this.outlined
&& items
.length
) {
10133 this.outlineSelectWidget
.addItems( items
, index
);
10134 this.selectFirstSelectablePage();
10136 this.stackLayout
.addItems( pages
, index
);
10137 this.emit( 'add', pages
, index
);
10143 * Remove the specified pages from the booklet layout.
10145 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
10147 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
10151 OO
.ui
.BookletLayout
.prototype.removePages = function ( pages
) {
10152 var i
, len
, name
, page
,
10155 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
10157 name
= page
.getName();
10158 delete this.pages
[ name
];
10159 if ( this.outlined
) {
10160 items
.push( this.outlineSelectWidget
.getItemFromData( name
) );
10161 page
.setOutlineItem( null );
10164 if ( this.outlined
&& items
.length
) {
10165 this.outlineSelectWidget
.removeItems( items
);
10166 this.selectFirstSelectablePage();
10168 this.stackLayout
.removeItems( pages
);
10169 this.emit( 'remove', pages
);
10175 * Clear all pages from the booklet layout.
10177 * To remove only a subset of pages from the booklet, use the #removePages method.
10182 OO
.ui
.BookletLayout
.prototype.clearPages = function () {
10184 pages
= this.stackLayout
.getItems();
10187 this.currentPageName
= null;
10188 if ( this.outlined
) {
10189 this.outlineSelectWidget
.clearItems();
10190 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
10191 pages
[ i
].setOutlineItem( null );
10194 this.stackLayout
.clearItems();
10196 this.emit( 'remove', pages
);
10202 * Set the current page by symbolic name.
10205 * @param {string} name Symbolic name of page
10207 OO
.ui
.BookletLayout
.prototype.setPage = function ( name
) {
10210 page
= this.pages
[ name
],
10211 previousPage
= this.currentPageName
&& this.pages
[ this.currentPageName
];
10213 if ( name
!== this.currentPageName
) {
10214 if ( this.outlined
) {
10215 selectedItem
= this.outlineSelectWidget
.getSelectedItem();
10216 if ( selectedItem
&& selectedItem
.getData() !== name
) {
10217 this.outlineSelectWidget
.selectItemByData( name
);
10221 if ( previousPage
) {
10222 previousPage
.setActive( false );
10223 // Blur anything focused if the next page doesn't have anything focusable.
10224 // This is not needed if the next page has something focusable (because once it is focused
10225 // this blur happens automatically). If the layout is non-continuous, this check is
10226 // meaningless because the next page is not visible yet and thus can't hold focus.
10229 this.stackLayout
.continuous
&&
10230 OO
.ui
.findFocusable( page
.$element
).length
!== 0
10232 $focused
= previousPage
.$element
.find( ':focus' );
10233 if ( $focused
.length
) {
10234 $focused
[ 0 ].blur();
10238 this.currentPageName
= name
;
10239 page
.setActive( true );
10240 this.stackLayout
.setItem( page
);
10241 if ( !this.stackLayout
.continuous
&& previousPage
) {
10242 // This should not be necessary, since any inputs on the previous page should have been
10243 // blurred when it was hidden, but browsers are not very consistent about this.
10244 $focused
= previousPage
.$element
.find( ':focus' );
10245 if ( $focused
.length
) {
10246 $focused
[ 0 ].blur();
10249 this.emit( 'set', page
);
10255 * Select the first selectable page.
10259 OO
.ui
.BookletLayout
.prototype.selectFirstSelectablePage = function () {
10260 if ( !this.outlineSelectWidget
.getSelectedItem() ) {
10261 this.outlineSelectWidget
.selectItem( this.outlineSelectWidget
.getFirstSelectableItem() );
10268 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
10269 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
10270 * select which one to display. By default, only one card is displayed at a time. When a user
10271 * navigates to a new card, the index layout automatically focuses on the first focusable element,
10272 * unless the default setting is changed.
10274 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
10277 * // Example of a IndexLayout that contains two CardLayouts.
10279 * function CardOneLayout( name, config ) {
10280 * CardOneLayout.parent.call( this, name, config );
10281 * this.$element.append( '<p>First card</p>' );
10283 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
10284 * CardOneLayout.prototype.setupTabItem = function () {
10285 * this.tabItem.setLabel( 'Card one' );
10288 * var card1 = new CardOneLayout( 'one' ),
10289 * card2 = new CardLayout( 'two', { label: 'Card two' } );
10291 * card2.$element.append( '<p>Second card</p>' );
10293 * var index = new OO.ui.IndexLayout();
10295 * index.addCards ( [ card1, card2 ] );
10296 * $( 'body' ).append( index.$element );
10299 * @extends OO.ui.MenuLayout
10302 * @param {Object} [config] Configuration options
10303 * @cfg {boolean} [continuous=false] Show all cards, one after another
10304 * @cfg {boolean} [expanded=true] Expand the content panel to fill the entire parent element.
10305 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
10307 OO
.ui
.IndexLayout
= function OoUiIndexLayout( config
) {
10308 // Configuration initialization
10309 config
= $.extend( {}, config
, { menuPosition
: 'top' } );
10311 // Parent constructor
10312 OO
.ui
.IndexLayout
.parent
.call( this, config
);
10315 this.currentCardName
= null;
10317 this.ignoreFocus
= false;
10318 this.stackLayout
= new OO
.ui
.StackLayout( {
10319 continuous
: !!config
.continuous
,
10320 expanded
: config
.expanded
10322 this.$content
.append( this.stackLayout
.$element
);
10323 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
10325 this.tabSelectWidget
= new OO
.ui
.TabSelectWidget();
10326 this.tabPanel
= new OO
.ui
.PanelLayout();
10327 this.$menu
.append( this.tabPanel
.$element
);
10329 this.toggleMenu( true );
10332 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
10333 this.tabSelectWidget
.connect( this, { select
: 'onTabSelectWidgetSelect' } );
10334 if ( this.autoFocus
) {
10335 // Event 'focus' does not bubble, but 'focusin' does
10336 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
10340 this.$element
.addClass( 'oo-ui-indexLayout' );
10341 this.stackLayout
.$element
.addClass( 'oo-ui-indexLayout-stackLayout' );
10342 this.tabPanel
.$element
10343 .addClass( 'oo-ui-indexLayout-tabPanel' )
10344 .append( this.tabSelectWidget
.$element
);
10349 OO
.inheritClass( OO
.ui
.IndexLayout
, OO
.ui
.MenuLayout
);
10354 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
10356 * @param {OO.ui.CardLayout} card Current card
10360 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
10363 * @param {OO.ui.CardLayout[]} card Added cards
10364 * @param {number} index Index cards were added at
10368 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
10369 * {@link #removeCards removed} from the index.
10372 * @param {OO.ui.CardLayout[]} cards Removed cards
10378 * Handle stack layout focus.
10381 * @param {jQuery.Event} e Focusin event
10383 OO
.ui
.IndexLayout
.prototype.onStackLayoutFocus = function ( e
) {
10386 // Find the card that an element was focused within
10387 $target
= $( e
.target
).closest( '.oo-ui-cardLayout' );
10388 for ( name
in this.cards
) {
10389 // Check for card match, exclude current card to find only card changes
10390 if ( this.cards
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentCardName
) {
10391 this.setCard( name
);
10398 * Handle stack layout set events.
10401 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
10403 OO
.ui
.IndexLayout
.prototype.onStackLayoutSet = function ( card
) {
10406 card
.scrollElementIntoView( { complete: function () {
10407 if ( layout
.autoFocus
) {
10415 * Focus the first input in the current card.
10417 * If no card is selected, the first selectable card will be selected.
10418 * If the focus is already in an element on the current card, nothing will happen.
10419 * @param {number} [itemIndex] A specific item to focus on
10421 OO
.ui
.IndexLayout
.prototype.focus = function ( itemIndex
) {
10423 items
= this.stackLayout
.getItems();
10425 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
10426 card
= items
[ itemIndex
];
10428 card
= this.stackLayout
.getCurrentItem();
10432 this.selectFirstSelectableCard();
10433 card
= this.stackLayout
.getCurrentItem();
10438 // Only change the focus if is not already in the current page
10439 if ( !OO
.ui
.contains( card
.$element
[ 0 ], this.getElementDocument().activeElement
, true ) ) {
10445 * Find the first focusable input in the index layout and focus
10448 OO
.ui
.IndexLayout
.prototype.focusFirstFocusable = function () {
10449 OO
.ui
.findFocusable( this.stackLayout
.$element
).focus();
10453 * Handle tab widget select events.
10456 * @param {OO.ui.OptionWidget|null} item Selected item
10458 OO
.ui
.IndexLayout
.prototype.onTabSelectWidgetSelect = function ( item
) {
10460 this.setCard( item
.getData() );
10465 * Get the card closest to the specified card.
10467 * @param {OO.ui.CardLayout} card Card to use as a reference point
10468 * @return {OO.ui.CardLayout|null} Card closest to the specified card
10470 OO
.ui
.IndexLayout
.prototype.getClosestCard = function ( card
) {
10471 var next
, prev
, level
,
10472 cards
= this.stackLayout
.getItems(),
10473 index
= cards
.indexOf( card
);
10475 if ( index
!== -1 ) {
10476 next
= cards
[ index
+ 1 ];
10477 prev
= cards
[ index
- 1 ];
10478 // Prefer adjacent cards at the same level
10479 level
= this.tabSelectWidget
.getItemFromData( card
.getName() ).getLevel();
10482 level
=== this.tabSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
10488 level
=== this.tabSelectWidget
.getItemFromData( next
.getName() ).getLevel()
10493 return prev
|| next
|| null;
10497 * Get the tabs widget.
10499 * @return {OO.ui.TabSelectWidget} Tabs widget
10501 OO
.ui
.IndexLayout
.prototype.getTabs = function () {
10502 return this.tabSelectWidget
;
10506 * Get a card by its symbolic name.
10508 * @param {string} name Symbolic name of card
10509 * @return {OO.ui.CardLayout|undefined} Card, if found
10511 OO
.ui
.IndexLayout
.prototype.getCard = function ( name
) {
10512 return this.cards
[ name
];
10516 * Get the current card.
10518 * @return {OO.ui.CardLayout|undefined} Current card, if found
10520 OO
.ui
.IndexLayout
.prototype.getCurrentCard = function () {
10521 var name
= this.getCurrentCardName();
10522 return name
? this.getCard( name
) : undefined;
10526 * Get the symbolic name of the current card.
10528 * @return {string|null} Symbolic name of the current card
10530 OO
.ui
.IndexLayout
.prototype.getCurrentCardName = function () {
10531 return this.currentCardName
;
10535 * Add cards to the index layout
10537 * When cards are added with the same names as existing cards, the existing cards will be
10538 * automatically removed before the new cards are added.
10540 * @param {OO.ui.CardLayout[]} cards Cards to add
10541 * @param {number} index Index of the insertion point
10545 OO
.ui
.IndexLayout
.prototype.addCards = function ( cards
, index
) {
10546 var i
, len
, name
, card
, item
, currentIndex
,
10547 stackLayoutCards
= this.stackLayout
.getItems(),
10551 // Remove cards with same names
10552 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10554 name
= card
.getName();
10556 if ( Object
.prototype.hasOwnProperty
.call( this.cards
, name
) ) {
10557 // Correct the insertion index
10558 currentIndex
= stackLayoutCards
.indexOf( this.cards
[ name
] );
10559 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
10562 remove
.push( this.cards
[ name
] );
10565 if ( remove
.length
) {
10566 this.removeCards( remove
);
10570 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10572 name
= card
.getName();
10573 this.cards
[ card
.getName() ] = card
;
10574 item
= new OO
.ui
.TabOptionWidget( { data
: name
} );
10575 card
.setTabItem( item
);
10576 items
.push( item
);
10579 if ( items
.length
) {
10580 this.tabSelectWidget
.addItems( items
, index
);
10581 this.selectFirstSelectableCard();
10583 this.stackLayout
.addItems( cards
, index
);
10584 this.emit( 'add', cards
, index
);
10590 * Remove the specified cards from the index layout.
10592 * To remove all cards from the index, you may wish to use the #clearCards method instead.
10594 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
10598 OO
.ui
.IndexLayout
.prototype.removeCards = function ( cards
) {
10599 var i
, len
, name
, card
,
10602 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10604 name
= card
.getName();
10605 delete this.cards
[ name
];
10606 items
.push( this.tabSelectWidget
.getItemFromData( name
) );
10607 card
.setTabItem( null );
10609 if ( items
.length
) {
10610 this.tabSelectWidget
.removeItems( items
);
10611 this.selectFirstSelectableCard();
10613 this.stackLayout
.removeItems( cards
);
10614 this.emit( 'remove', cards
);
10620 * Clear all cards from the index layout.
10622 * To remove only a subset of cards from the index, use the #removeCards method.
10627 OO
.ui
.IndexLayout
.prototype.clearCards = function () {
10629 cards
= this.stackLayout
.getItems();
10632 this.currentCardName
= null;
10633 this.tabSelectWidget
.clearItems();
10634 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10635 cards
[ i
].setTabItem( null );
10637 this.stackLayout
.clearItems();
10639 this.emit( 'remove', cards
);
10645 * Set the current card by symbolic name.
10648 * @param {string} name Symbolic name of card
10650 OO
.ui
.IndexLayout
.prototype.setCard = function ( name
) {
10653 card
= this.cards
[ name
],
10654 previousCard
= this.currentCardName
&& this.cards
[ this.currentCardName
];
10656 if ( name
!== this.currentCardName
) {
10657 selectedItem
= this.tabSelectWidget
.getSelectedItem();
10658 if ( selectedItem
&& selectedItem
.getData() !== name
) {
10659 this.tabSelectWidget
.selectItemByData( name
);
10662 if ( previousCard
) {
10663 previousCard
.setActive( false );
10664 // Blur anything focused if the next card doesn't have anything focusable.
10665 // This is not needed if the next card has something focusable (because once it is focused
10666 // this blur happens automatically). If the layout is non-continuous, this check is
10667 // meaningless because the next card is not visible yet and thus can't hold focus.
10670 this.stackLayout
.continuous
&&
10671 OO
.ui
.findFocusable( card
.$element
).length
!== 0
10673 $focused
= previousCard
.$element
.find( ':focus' );
10674 if ( $focused
.length
) {
10675 $focused
[ 0 ].blur();
10679 this.currentCardName
= name
;
10680 card
.setActive( true );
10681 this.stackLayout
.setItem( card
);
10682 if ( !this.stackLayout
.continuous
&& previousCard
) {
10683 // This should not be necessary, since any inputs on the previous card should have been
10684 // blurred when it was hidden, but browsers are not very consistent about this.
10685 $focused
= previousCard
.$element
.find( ':focus' );
10686 if ( $focused
.length
) {
10687 $focused
[ 0 ].blur();
10690 this.emit( 'set', card
);
10696 * Select the first selectable card.
10700 OO
.ui
.IndexLayout
.prototype.selectFirstSelectableCard = function () {
10701 if ( !this.tabSelectWidget
.getSelectedItem() ) {
10702 this.tabSelectWidget
.selectItem( this.tabSelectWidget
.getFirstSelectableItem() );
10709 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10710 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10713 * // Example of a panel layout
10714 * var panel = new OO.ui.PanelLayout( {
10718 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10720 * $( 'body' ).append( panel.$element );
10723 * @extends OO.ui.Layout
10726 * @param {Object} [config] Configuration options
10727 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10728 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10729 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10730 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10732 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
10733 // Configuration initialization
10734 config
= $.extend( {
10741 // Parent constructor
10742 OO
.ui
.PanelLayout
.parent
.call( this, config
);
10745 this.$element
.addClass( 'oo-ui-panelLayout' );
10746 if ( config
.scrollable
) {
10747 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
10749 if ( config
.padded
) {
10750 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
10752 if ( config
.expanded
) {
10753 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
10755 if ( config
.framed
) {
10756 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
10762 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
10767 * Focus the panel layout
10769 * The default implementation just focuses the first focusable element in the panel
10771 OO
.ui
.PanelLayout
.prototype.focus = function () {
10772 OO
.ui
.findFocusable( this.$element
).focus();
10776 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
10777 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
10778 * rather extended to include the required content and functionality.
10780 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
10781 * item is customized (with a label) using the #setupTabItem method. See
10782 * {@link OO.ui.IndexLayout IndexLayout} for an example.
10785 * @extends OO.ui.PanelLayout
10788 * @param {string} name Unique symbolic name of card
10789 * @param {Object} [config] Configuration options
10790 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] Label for card's tab
10792 OO
.ui
.CardLayout
= function OoUiCardLayout( name
, config
) {
10793 // Allow passing positional parameters inside the config object
10794 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
10796 name
= config
.name
;
10799 // Configuration initialization
10800 config
= $.extend( { scrollable
: true }, config
);
10802 // Parent constructor
10803 OO
.ui
.CardLayout
.parent
.call( this, config
);
10807 this.label
= config
.label
;
10808 this.tabItem
= null;
10809 this.active
= false;
10812 this.$element
.addClass( 'oo-ui-cardLayout' );
10817 OO
.inheritClass( OO
.ui
.CardLayout
, OO
.ui
.PanelLayout
);
10822 * An 'active' event is emitted when the card becomes active. Cards become active when they are
10823 * shown in a index layout that is configured to display only one card at a time.
10826 * @param {boolean} active Card is active
10832 * Get the symbolic name of the card.
10834 * @return {string} Symbolic name of card
10836 OO
.ui
.CardLayout
.prototype.getName = function () {
10841 * Check if card is active.
10843 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
10844 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
10846 * @return {boolean} Card is active
10848 OO
.ui
.CardLayout
.prototype.isActive = function () {
10849 return this.active
;
10855 * The tab item allows users to access the card from the index's tab
10856 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
10858 * @return {OO.ui.TabOptionWidget|null} Tab option widget
10860 OO
.ui
.CardLayout
.prototype.getTabItem = function () {
10861 return this.tabItem
;
10865 * Set or unset the tab item.
10867 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
10868 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
10869 * level), use #setupTabItem instead of this method.
10871 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
10874 OO
.ui
.CardLayout
.prototype.setTabItem = function ( tabItem
) {
10875 this.tabItem
= tabItem
|| null;
10877 this.setupTabItem();
10883 * Set up the tab item.
10885 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
10886 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
10887 * the #setTabItem method instead.
10889 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
10892 OO
.ui
.CardLayout
.prototype.setupTabItem = function () {
10893 if ( this.label
) {
10894 this.tabItem
.setLabel( this.label
);
10900 * Set the card to its 'active' state.
10902 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
10903 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
10904 * context, setting the active state on a card does nothing.
10906 * @param {boolean} value Card is active
10909 OO
.ui
.CardLayout
.prototype.setActive = function ( active
) {
10912 if ( active
!== this.active
) {
10913 this.active
= active
;
10914 this.$element
.toggleClass( 'oo-ui-cardLayout-active', this.active
);
10915 this.emit( 'active', this.active
);
10920 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
10921 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
10922 * rather extended to include the required content and functionality.
10924 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
10925 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
10926 * {@link OO.ui.BookletLayout BookletLayout} for an example.
10929 * @extends OO.ui.PanelLayout
10932 * @param {string} name Unique symbolic name of page
10933 * @param {Object} [config] Configuration options
10935 OO
.ui
.PageLayout
= function OoUiPageLayout( name
, config
) {
10936 // Allow passing positional parameters inside the config object
10937 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
10939 name
= config
.name
;
10942 // Configuration initialization
10943 config
= $.extend( { scrollable
: true }, config
);
10945 // Parent constructor
10946 OO
.ui
.PageLayout
.parent
.call( this, config
);
10950 this.outlineItem
= null;
10951 this.active
= false;
10954 this.$element
.addClass( 'oo-ui-pageLayout' );
10959 OO
.inheritClass( OO
.ui
.PageLayout
, OO
.ui
.PanelLayout
);
10964 * An 'active' event is emitted when the page becomes active. Pages become active when they are
10965 * shown in a booklet layout that is configured to display only one page at a time.
10968 * @param {boolean} active Page is active
10974 * Get the symbolic name of the page.
10976 * @return {string} Symbolic name of page
10978 OO
.ui
.PageLayout
.prototype.getName = function () {
10983 * Check if page is active.
10985 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
10986 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
10988 * @return {boolean} Page is active
10990 OO
.ui
.PageLayout
.prototype.isActive = function () {
10991 return this.active
;
10995 * Get outline item.
10997 * The outline item allows users to access the page from the booklet's outline
10998 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
11000 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
11002 OO
.ui
.PageLayout
.prototype.getOutlineItem = function () {
11003 return this.outlineItem
;
11007 * Set or unset the outline item.
11009 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
11010 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
11011 * level), use #setupOutlineItem instead of this method.
11013 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
11016 OO
.ui
.PageLayout
.prototype.setOutlineItem = function ( outlineItem
) {
11017 this.outlineItem
= outlineItem
|| null;
11018 if ( outlineItem
) {
11019 this.setupOutlineItem();
11025 * Set up the outline item.
11027 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
11028 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
11029 * the #setOutlineItem method instead.
11031 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
11034 OO
.ui
.PageLayout
.prototype.setupOutlineItem = function () {
11039 * Set the page to its 'active' state.
11041 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
11042 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
11043 * context, setting the active state on a page does nothing.
11045 * @param {boolean} value Page is active
11048 OO
.ui
.PageLayout
.prototype.setActive = function ( active
) {
11051 if ( active
!== this.active
) {
11052 this.active
= active
;
11053 this.$element
.toggleClass( 'oo-ui-pageLayout-active', active
);
11054 this.emit( 'active', this.active
);
11059 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
11060 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
11061 * by setting the #continuous option to 'true'.
11064 * // A stack layout with two panels, configured to be displayed continously
11065 * var myStack = new OO.ui.StackLayout( {
11067 * new OO.ui.PanelLayout( {
11068 * $content: $( '<p>Panel One</p>' ),
11072 * new OO.ui.PanelLayout( {
11073 * $content: $( '<p>Panel Two</p>' ),
11080 * $( 'body' ).append( myStack.$element );
11083 * @extends OO.ui.PanelLayout
11084 * @mixins OO.ui.mixin.GroupElement
11087 * @param {Object} [config] Configuration options
11088 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
11089 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
11091 OO
.ui
.StackLayout
= function OoUiStackLayout( config
) {
11092 // Configuration initialization
11093 config
= $.extend( { scrollable
: true }, config
);
11095 // Parent constructor
11096 OO
.ui
.StackLayout
.parent
.call( this, config
);
11098 // Mixin constructors
11099 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11102 this.currentItem
= null;
11103 this.continuous
= !!config
.continuous
;
11106 this.$element
.addClass( 'oo-ui-stackLayout' );
11107 if ( this.continuous
) {
11108 this.$element
.addClass( 'oo-ui-stackLayout-continuous' );
11109 this.$element
.on( 'scroll', OO
.ui
.debounce( this.onScroll
.bind( this ), 250 ) );
11111 if ( Array
.isArray( config
.items
) ) {
11112 this.addItems( config
.items
);
11118 OO
.inheritClass( OO
.ui
.StackLayout
, OO
.ui
.PanelLayout
);
11119 OO
.mixinClass( OO
.ui
.StackLayout
, OO
.ui
.mixin
.GroupElement
);
11124 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
11125 * {@link #clearItems cleared} or {@link #setItem displayed}.
11128 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
11132 * When used in continuous mode, this event is emitted when the user scrolls down
11133 * far enough such that currentItem is no longer visible.
11135 * @event visibleItemChange
11136 * @param {OO.ui.PanelLayout} panel The next visible item in the layout
11142 * Handle scroll events from the layout element
11144 * @param {jQuery.Event} e
11145 * @fires visibleItemChange
11147 OO
.ui
.StackLayout
.prototype.onScroll = function () {
11149 len
= this.items
.length
,
11150 currentIndex
= this.items
.indexOf( this.currentItem
),
11151 newIndex
= currentIndex
,
11152 containerRect
= this.$element
[ 0 ].getBoundingClientRect();
11154 if ( !containerRect
|| ( !containerRect
.top
&& !containerRect
.bottom
) ) {
11155 // Can't get bounding rect, possibly not attached.
11159 function getRect( item
) {
11160 return item
.$element
[ 0 ].getBoundingClientRect();
11163 function isVisible( item
) {
11164 var rect
= getRect( item
);
11165 return rect
.bottom
> containerRect
.top
&& rect
.top
< containerRect
.bottom
;
11168 currentRect
= getRect( this.currentItem
);
11170 if ( currentRect
.bottom
< containerRect
.top
) {
11171 // Scrolled down past current item
11172 while ( ++newIndex
< len
) {
11173 if ( isVisible( this.items
[ newIndex
] ) ) {
11177 } else if ( currentRect
.top
> containerRect
.bottom
) {
11178 // Scrolled up past current item
11179 while ( --newIndex
>= 0 ) {
11180 if ( isVisible( this.items
[ newIndex
] ) ) {
11186 if ( newIndex
!== currentIndex
) {
11187 this.emit( 'visibleItemChange', this.items
[ newIndex
] );
11192 * Get the current panel.
11194 * @return {OO.ui.Layout|null}
11196 OO
.ui
.StackLayout
.prototype.getCurrentItem = function () {
11197 return this.currentItem
;
11201 * Unset the current item.
11204 * @param {OO.ui.StackLayout} layout
11207 OO
.ui
.StackLayout
.prototype.unsetCurrentItem = function () {
11208 var prevItem
= this.currentItem
;
11209 if ( prevItem
=== null ) {
11213 this.currentItem
= null;
11214 this.emit( 'set', null );
11218 * Add panel layouts to the stack layout.
11220 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
11221 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
11224 * @param {OO.ui.Layout[]} items Panels to add
11225 * @param {number} [index] Index of the insertion point
11228 OO
.ui
.StackLayout
.prototype.addItems = function ( items
, index
) {
11229 // Update the visibility
11230 this.updateHiddenState( items
, this.currentItem
);
11233 OO
.ui
.mixin
.GroupElement
.prototype.addItems
.call( this, items
, index
);
11235 if ( !this.currentItem
&& items
.length
) {
11236 this.setItem( items
[ 0 ] );
11243 * Remove the specified panels from the stack layout.
11245 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
11246 * you may wish to use the #clearItems method instead.
11248 * @param {OO.ui.Layout[]} items Panels to remove
11252 OO
.ui
.StackLayout
.prototype.removeItems = function ( items
) {
11254 OO
.ui
.mixin
.GroupElement
.prototype.removeItems
.call( this, items
);
11256 if ( items
.indexOf( this.currentItem
) !== -1 ) {
11257 if ( this.items
.length
) {
11258 this.setItem( this.items
[ 0 ] );
11260 this.unsetCurrentItem();
11268 * Clear all panels from the stack layout.
11270 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
11271 * a subset of panels, use the #removeItems method.
11276 OO
.ui
.StackLayout
.prototype.clearItems = function () {
11277 this.unsetCurrentItem();
11278 OO
.ui
.mixin
.GroupElement
.prototype.clearItems
.call( this );
11284 * Show the specified panel.
11286 * If another panel is currently displayed, it will be hidden.
11288 * @param {OO.ui.Layout} item Panel to show
11292 OO
.ui
.StackLayout
.prototype.setItem = function ( item
) {
11293 if ( item
!== this.currentItem
) {
11294 this.updateHiddenState( this.items
, item
);
11296 if ( this.items
.indexOf( item
) !== -1 ) {
11297 this.currentItem
= item
;
11298 this.emit( 'set', item
);
11300 this.unsetCurrentItem();
11308 * Update the visibility of all items in case of non-continuous view.
11310 * Ensure all items are hidden except for the selected one.
11311 * This method does nothing when the stack is continuous.
11314 * @param {OO.ui.Layout[]} items Item list iterate over
11315 * @param {OO.ui.Layout} [selectedItem] Selected item to show
11317 OO
.ui
.StackLayout
.prototype.updateHiddenState = function ( items
, selectedItem
) {
11320 if ( !this.continuous
) {
11321 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
11322 if ( !selectedItem
|| selectedItem
!== items
[ i
] ) {
11323 items
[ i
].$element
.addClass( 'oo-ui-element-hidden' );
11326 if ( selectedItem
) {
11327 selectedItem
.$element
.removeClass( 'oo-ui-element-hidden' );
11333 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
11334 * items), with small margins between them. Convenient when you need to put a number of block-level
11335 * widgets on a single line next to each other.
11337 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
11340 * // HorizontalLayout with a text input and a label
11341 * var layout = new OO.ui.HorizontalLayout( {
11343 * new OO.ui.LabelWidget( { label: 'Label' } ),
11344 * new OO.ui.TextInputWidget( { value: 'Text' } )
11347 * $( 'body' ).append( layout.$element );
11350 * @extends OO.ui.Layout
11351 * @mixins OO.ui.mixin.GroupElement
11354 * @param {Object} [config] Configuration options
11355 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
11357 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
11358 // Configuration initialization
11359 config
= config
|| {};
11361 // Parent constructor
11362 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
11364 // Mixin constructors
11365 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11368 this.$element
.addClass( 'oo-ui-horizontalLayout' );
11369 if ( Array
.isArray( config
.items
) ) {
11370 this.addItems( config
.items
);
11376 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
11377 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);
11380 * BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11381 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11382 * and {@link OO.ui.ListToolGroup ListToolGroup}). The {@link OO.ui.Tool tools} in a BarToolGroup are
11383 * displayed by icon in a single row. The title of the tool is displayed when users move the mouse over
11386 * BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar is
11390 * // Example of a BarToolGroup with two tools
11391 * var toolFactory = new OO.ui.ToolFactory();
11392 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11393 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11395 * // We will be placing status text in this element when tools are used
11396 * var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' );
11398 * // Define the tools that we're going to place in our toolbar
11400 * // Create a class inheriting from OO.ui.Tool
11401 * function PictureTool() {
11402 * PictureTool.parent.apply( this, arguments );
11404 * OO.inheritClass( PictureTool, OO.ui.Tool );
11405 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
11406 * // of 'icon' and 'title' (displayed icon and text).
11407 * PictureTool.static.name = 'picture';
11408 * PictureTool.static.icon = 'picture';
11409 * PictureTool.static.title = 'Insert picture';
11410 * // Defines the action that will happen when this tool is selected (clicked).
11411 * PictureTool.prototype.onSelect = function () {
11412 * $area.text( 'Picture tool clicked!' );
11413 * // Never display this tool as "active" (selected).
11414 * this.setActive( false );
11416 * // Make this tool available in our toolFactory and thus our toolbar
11417 * toolFactory.register( PictureTool );
11419 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
11420 * // little popup window (a PopupWidget).
11421 * function HelpTool( toolGroup, config ) {
11422 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11427 * this.popup.$body.append( '<p>I am helpful!</p>' );
11429 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11430 * HelpTool.static.name = 'help';
11431 * HelpTool.static.icon = 'help';
11432 * HelpTool.static.title = 'Help';
11433 * toolFactory.register( HelpTool );
11435 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11436 * // used once (but not all defined tools must be used).
11439 * // 'bar' tool groups display tools by icon only
11441 * include: [ 'picture', 'help' ]
11445 * // Create some UI around the toolbar and place it in the document
11446 * var frame = new OO.ui.PanelLayout( {
11450 * var contentFrame = new OO.ui.PanelLayout( {
11454 * frame.$element.append(
11455 * toolbar.$element,
11456 * contentFrame.$element.append( $area )
11458 * $( 'body' ).append( frame.$element );
11460 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11462 * toolbar.initialize();
11464 * For more information about how to add tools to a bar tool group, please see {@link OO.ui.ToolGroup toolgroup}.
11465 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11467 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11470 * @extends OO.ui.ToolGroup
11473 * @param {OO.ui.Toolbar} toolbar
11474 * @param {Object} [config] Configuration options
11476 OO
.ui
.BarToolGroup
= function OoUiBarToolGroup( toolbar
, config
) {
11477 // Allow passing positional parameters inside the config object
11478 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11480 toolbar
= config
.toolbar
;
11483 // Parent constructor
11484 OO
.ui
.BarToolGroup
.parent
.call( this, toolbar
, config
);
11487 this.$element
.addClass( 'oo-ui-barToolGroup' );
11492 OO
.inheritClass( OO
.ui
.BarToolGroup
, OO
.ui
.ToolGroup
);
11494 /* Static Properties */
11496 OO
.ui
.BarToolGroup
.static.titleTooltips
= true;
11498 OO
.ui
.BarToolGroup
.static.accelTooltips
= true;
11500 OO
.ui
.BarToolGroup
.static.name
= 'bar';
11503 * PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup}
11504 * and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup--an overlaid menu or list of tools with an
11505 * optional icon and label. This class can be used for other base classes that also use this functionality.
11509 * @extends OO.ui.ToolGroup
11510 * @mixins OO.ui.mixin.IconElement
11511 * @mixins OO.ui.mixin.IndicatorElement
11512 * @mixins OO.ui.mixin.LabelElement
11513 * @mixins OO.ui.mixin.TitledElement
11514 * @mixins OO.ui.mixin.ClippableElement
11515 * @mixins OO.ui.mixin.TabIndexedElement
11518 * @param {OO.ui.Toolbar} toolbar
11519 * @param {Object} [config] Configuration options
11520 * @cfg {string} [header] Text to display at the top of the popup
11522 OO
.ui
.PopupToolGroup
= function OoUiPopupToolGroup( toolbar
, config
) {
11523 // Allow passing positional parameters inside the config object
11524 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11526 toolbar
= config
.toolbar
;
11529 // Configuration initialization
11530 config
= config
|| {};
11532 // Parent constructor
11533 OO
.ui
.PopupToolGroup
.parent
.call( this, toolbar
, config
);
11536 this.active
= false;
11537 this.dragging
= false;
11538 this.onBlurHandler
= this.onBlur
.bind( this );
11539 this.$handle
= $( '<span>' );
11541 // Mixin constructors
11542 OO
.ui
.mixin
.IconElement
.call( this, config
);
11543 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
11544 OO
.ui
.mixin
.LabelElement
.call( this, config
);
11545 OO
.ui
.mixin
.TitledElement
.call( this, config
);
11546 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
11547 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
11551 keydown
: this.onHandleMouseKeyDown
.bind( this ),
11552 keyup
: this.onHandleMouseKeyUp
.bind( this ),
11553 mousedown
: this.onHandleMouseKeyDown
.bind( this ),
11554 mouseup
: this.onHandleMouseKeyUp
.bind( this )
11559 .addClass( 'oo-ui-popupToolGroup-handle' )
11560 .append( this.$icon
, this.$label
, this.$indicator
);
11561 // If the pop-up should have a header, add it to the top of the toolGroup.
11562 // Note: If this feature is useful for other widgets, we could abstract it into an
11563 // OO.ui.HeaderedElement mixin constructor.
11564 if ( config
.header
!== undefined ) {
11566 .prepend( $( '<span>' )
11567 .addClass( 'oo-ui-popupToolGroup-header' )
11568 .text( config
.header
)
11572 .addClass( 'oo-ui-popupToolGroup' )
11573 .prepend( this.$handle
);
11578 OO
.inheritClass( OO
.ui
.PopupToolGroup
, OO
.ui
.ToolGroup
);
11579 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.IconElement
);
11580 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.IndicatorElement
);
11581 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.LabelElement
);
11582 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.TitledElement
);
11583 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.ClippableElement
);
11584 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.TabIndexedElement
);
11591 OO
.ui
.PopupToolGroup
.prototype.setDisabled = function () {
11593 OO
.ui
.PopupToolGroup
.parent
.prototype.setDisabled
.apply( this, arguments
);
11595 if ( this.isDisabled() && this.isElementAttached() ) {
11596 this.setActive( false );
11601 * Handle focus being lost.
11603 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
11606 * @param {jQuery.Event} e Mouse up or key up event
11608 OO
.ui
.PopupToolGroup
.prototype.onBlur = function ( e
) {
11609 // Only deactivate when clicking outside the dropdown element
11610 if ( $( e
.target
).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element
[ 0 ] ) {
11611 this.setActive( false );
11618 OO
.ui
.PopupToolGroup
.prototype.onMouseKeyUp = function ( e
) {
11619 // Only close toolgroup when a tool was actually selected
11621 !this.isDisabled() && this.pressed
&& this.pressed
=== this.getTargetTool( e
) &&
11622 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11624 this.setActive( false );
11626 return OO
.ui
.PopupToolGroup
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11630 * Handle mouse up and key up events.
11633 * @param {jQuery.Event} e Mouse up or key up event
11635 OO
.ui
.PopupToolGroup
.prototype.onHandleMouseKeyUp = function ( e
) {
11637 !this.isDisabled() &&
11638 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11645 * Handle mouse down and key down events.
11648 * @param {jQuery.Event} e Mouse down or key down event
11650 OO
.ui
.PopupToolGroup
.prototype.onHandleMouseKeyDown = function ( e
) {
11652 !this.isDisabled() &&
11653 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11655 this.setActive( !this.active
);
11661 * Switch into 'active' mode.
11663 * When active, the popup is visible. A mouseup event anywhere in the document will trigger
11666 OO
.ui
.PopupToolGroup
.prototype.setActive = function ( value
) {
11667 var containerWidth
, containerLeft
;
11669 if ( this.active
!== value
) {
11670 this.active
= value
;
11672 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler
);
11673 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler
);
11675 this.$clippable
.css( 'left', '' );
11676 // Try anchoring the popup to the left first
11677 this.$element
.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
11678 this.toggleClipping( true );
11679 if ( this.isClippedHorizontally() ) {
11680 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
11681 this.toggleClipping( false );
11683 .removeClass( 'oo-ui-popupToolGroup-left' )
11684 .addClass( 'oo-ui-popupToolGroup-right' );
11685 this.toggleClipping( true );
11687 if ( this.isClippedHorizontally() ) {
11688 // Anchoring to the right also caused the popup to clip, so just make it fill the container
11689 containerWidth
= this.$clippableScrollableContainer
.width();
11690 containerLeft
= this.$clippableScrollableContainer
.offset().left
;
11692 this.toggleClipping( false );
11693 this.$element
.removeClass( 'oo-ui-popupToolGroup-right' );
11695 this.$clippable
.css( {
11696 left
: -( this.$element
.offset().left
- containerLeft
),
11697 width
: containerWidth
11701 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler
);
11702 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler
);
11703 this.$element
.removeClass(
11704 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
11706 this.toggleClipping( false );
11712 * ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11713 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11714 * and {@link OO.ui.BarToolGroup BarToolGroup}). The {@link OO.ui.Tool tools} in a ListToolGroup are displayed
11715 * by label in a dropdown menu. The title of the tool is used as the label text. The menu itself can be configured
11716 * with a label, icon, indicator, header, and title.
11718 * ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a ‘More’ option that
11719 * users can select to see the full list of tools. If a collapsed toolgroup is expanded, a ‘Fewer’ option permits
11720 * users to collapse the list again.
11722 * ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the toolbar is set up. The factory
11723 * requires the ListToolGroup's symbolic name, 'list', which is specified along with the other configurations. For more
11724 * information about how to add tools to a ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11727 * // Example of a ListToolGroup
11728 * var toolFactory = new OO.ui.ToolFactory();
11729 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11730 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11732 * // Configure and register two tools
11733 * function SettingsTool() {
11734 * SettingsTool.parent.apply( this, arguments );
11736 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11737 * SettingsTool.static.name = 'settings';
11738 * SettingsTool.static.icon = 'settings';
11739 * SettingsTool.static.title = 'Change settings';
11740 * SettingsTool.prototype.onSelect = function () {
11741 * this.setActive( false );
11743 * toolFactory.register( SettingsTool );
11744 * // Register two more tools, nothing interesting here
11745 * function StuffTool() {
11746 * StuffTool.parent.apply( this, arguments );
11748 * OO.inheritClass( StuffTool, OO.ui.Tool );
11749 * StuffTool.static.name = 'stuff';
11750 * StuffTool.static.icon = 'ellipsis';
11751 * StuffTool.static.title = 'Change the world';
11752 * StuffTool.prototype.onSelect = function () {
11753 * this.setActive( false );
11755 * toolFactory.register( StuffTool );
11758 * // Configurations for list toolgroup.
11760 * label: 'ListToolGroup',
11761 * indicator: 'down',
11763 * title: 'This is the title, displayed when user moves the mouse over the list toolgroup',
11764 * header: 'This is the header',
11765 * include: [ 'settings', 'stuff' ],
11766 * allowCollapse: ['stuff']
11770 * // Create some UI around the toolbar and place it in the document
11771 * var frame = new OO.ui.PanelLayout( {
11775 * frame.$element.append(
11778 * $( 'body' ).append( frame.$element );
11779 * // Build the toolbar. This must be done after the toolbar has been appended to the document.
11780 * toolbar.initialize();
11782 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11784 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11787 * @extends OO.ui.PopupToolGroup
11790 * @param {OO.ui.Toolbar} toolbar
11791 * @param {Object} [config] Configuration options
11792 * @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible tools
11793 * will only be displayed if users click the ‘More’ option displayed at the bottom of the list. If
11794 * the list is expanded, a ‘Fewer’ option permits users to collapse the list again. Any tools that
11795 * are included in the toolgroup, but are not designated as collapsible, will always be displayed.
11796 * To open a collapsible list in its expanded state, set #expanded to 'true'.
11797 * @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as collapsible.
11798 * Unless #expanded is set to true, the collapsible tools will be collapsed when the list is first opened.
11799 * @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools have
11800 * been designated as collapsible. When expanded is set to true, all tools in the group will be displayed
11801 * when the list is first opened. Users can collapse the list with a ‘Fewer’ option at the bottom.
11803 OO
.ui
.ListToolGroup
= function OoUiListToolGroup( toolbar
, config
) {
11804 // Allow passing positional parameters inside the config object
11805 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11807 toolbar
= config
.toolbar
;
11810 // Configuration initialization
11811 config
= config
|| {};
11813 // Properties (must be set before parent constructor, which calls #populate)
11814 this.allowCollapse
= config
.allowCollapse
;
11815 this.forceExpand
= config
.forceExpand
;
11816 this.expanded
= config
.expanded
!== undefined ? config
.expanded
: false;
11817 this.collapsibleTools
= [];
11819 // Parent constructor
11820 OO
.ui
.ListToolGroup
.parent
.call( this, toolbar
, config
);
11823 this.$element
.addClass( 'oo-ui-listToolGroup' );
11828 OO
.inheritClass( OO
.ui
.ListToolGroup
, OO
.ui
.PopupToolGroup
);
11830 /* Static Properties */
11832 OO
.ui
.ListToolGroup
.static.name
= 'list';
11839 OO
.ui
.ListToolGroup
.prototype.populate = function () {
11840 var i
, len
, allowCollapse
= [];
11842 OO
.ui
.ListToolGroup
.parent
.prototype.populate
.call( this );
11844 // Update the list of collapsible tools
11845 if ( this.allowCollapse
!== undefined ) {
11846 allowCollapse
= this.allowCollapse
;
11847 } else if ( this.forceExpand
!== undefined ) {
11848 allowCollapse
= OO
.simpleArrayDifference( Object
.keys( this.tools
), this.forceExpand
);
11851 this.collapsibleTools
= [];
11852 for ( i
= 0, len
= allowCollapse
.length
; i
< len
; i
++ ) {
11853 if ( this.tools
[ allowCollapse
[ i
] ] !== undefined ) {
11854 this.collapsibleTools
.push( this.tools
[ allowCollapse
[ i
] ] );
11858 // Keep at the end, even when tools are added
11859 this.$group
.append( this.getExpandCollapseTool().$element
);
11861 this.getExpandCollapseTool().toggle( this.collapsibleTools
.length
!== 0 );
11862 this.updateCollapsibleState();
11865 OO
.ui
.ListToolGroup
.prototype.getExpandCollapseTool = function () {
11866 var ExpandCollapseTool
;
11867 if ( this.expandCollapseTool
=== undefined ) {
11868 ExpandCollapseTool = function () {
11869 ExpandCollapseTool
.parent
.apply( this, arguments
);
11872 OO
.inheritClass( ExpandCollapseTool
, OO
.ui
.Tool
);
11874 ExpandCollapseTool
.prototype.onSelect = function () {
11875 this.toolGroup
.expanded
= !this.toolGroup
.expanded
;
11876 this.toolGroup
.updateCollapsibleState();
11877 this.setActive( false );
11879 ExpandCollapseTool
.prototype.onUpdateState = function () {
11880 // Do nothing. Tool interface requires an implementation of this function.
11883 ExpandCollapseTool
.static.name
= 'more-fewer';
11885 this.expandCollapseTool
= new ExpandCollapseTool( this );
11887 return this.expandCollapseTool
;
11893 OO
.ui
.ListToolGroup
.prototype.onMouseKeyUp = function ( e
) {
11894 // Do not close the popup when the user wants to show more/fewer tools
11896 $( e
.target
).closest( '.oo-ui-tool-name-more-fewer' ).length
&&
11897 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11899 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
11900 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
11901 return OO
.ui
.ListToolGroup
.parent
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11903 return OO
.ui
.ListToolGroup
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11907 OO
.ui
.ListToolGroup
.prototype.updateCollapsibleState = function () {
11910 this.getExpandCollapseTool()
11911 .setIcon( this.expanded
? 'collapse' : 'expand' )
11912 .setTitle( OO
.ui
.msg( this.expanded
? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
11914 for ( i
= 0, len
= this.collapsibleTools
.length
; i
< len
; i
++ ) {
11915 this.collapsibleTools
[ i
].toggle( this.expanded
);
11920 * MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11921 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.BarToolGroup BarToolGroup}
11922 * and {@link OO.ui.ListToolGroup ListToolGroup}). MenuToolGroups contain selectable {@link OO.ui.Tool tools},
11923 * which are displayed by label in a dropdown menu. The tool's title is used as the label text, and the
11924 * menu label is updated to reflect which tool or tools are currently selected. If no tools are selected,
11925 * the menu label is empty. The menu can be configured with an indicator, icon, title, and/or header.
11927 * MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar
11928 * is set up. Note that all tools must define an {@link OO.ui.Tool#onUpdateState onUpdateState} method if
11929 * a MenuToolGroup is used.
11932 * // Example of a MenuToolGroup
11933 * var toolFactory = new OO.ui.ToolFactory();
11934 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11935 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11937 * // We will be placing status text in this element when tools are used
11938 * var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the dropdown menu.' );
11940 * // Define the tools that we're going to place in our toolbar
11942 * function SettingsTool() {
11943 * SettingsTool.parent.apply( this, arguments );
11944 * this.reallyActive = false;
11946 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11947 * SettingsTool.static.name = 'settings';
11948 * SettingsTool.static.icon = 'settings';
11949 * SettingsTool.static.title = 'Change settings';
11950 * SettingsTool.prototype.onSelect = function () {
11951 * $area.text( 'Settings tool clicked!' );
11952 * // Toggle the active state on each click
11953 * this.reallyActive = !this.reallyActive;
11954 * this.setActive( this.reallyActive );
11955 * // To update the menu label
11956 * this.toolbar.emit( 'updateState' );
11958 * SettingsTool.prototype.onUpdateState = function () {
11960 * toolFactory.register( SettingsTool );
11962 * function StuffTool() {
11963 * StuffTool.parent.apply( this, arguments );
11964 * this.reallyActive = false;
11966 * OO.inheritClass( StuffTool, OO.ui.Tool );
11967 * StuffTool.static.name = 'stuff';
11968 * StuffTool.static.icon = 'ellipsis';
11969 * StuffTool.static.title = 'More stuff';
11970 * StuffTool.prototype.onSelect = function () {
11971 * $area.text( 'More stuff tool clicked!' );
11972 * // Toggle the active state on each click
11973 * this.reallyActive = !this.reallyActive;
11974 * this.setActive( this.reallyActive );
11975 * // To update the menu label
11976 * this.toolbar.emit( 'updateState' );
11978 * StuffTool.prototype.onUpdateState = function () {
11980 * toolFactory.register( StuffTool );
11982 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11983 * // used once (but not all defined tools must be used).
11987 * header: 'This is the (optional) header',
11988 * title: 'This is the (optional) title',
11989 * indicator: 'down',
11990 * include: [ 'settings', 'stuff' ]
11994 * // Create some UI around the toolbar and place it in the document
11995 * var frame = new OO.ui.PanelLayout( {
11999 * var contentFrame = new OO.ui.PanelLayout( {
12003 * frame.$element.append(
12004 * toolbar.$element,
12005 * contentFrame.$element.append( $area )
12007 * $( 'body' ).append( frame.$element );
12009 * // Here is where the toolbar is actually built. This must be done after inserting it into the
12011 * toolbar.initialize();
12012 * toolbar.emit( 'updateState' );
12014 * For more information about how to add tools to a MenuToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
12015 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki] [1].
12017 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
12020 * @extends OO.ui.PopupToolGroup
12023 * @param {OO.ui.Toolbar} toolbar
12024 * @param {Object} [config] Configuration options
12026 OO
.ui
.MenuToolGroup
= function OoUiMenuToolGroup( toolbar
, config
) {
12027 // Allow passing positional parameters inside the config object
12028 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
12030 toolbar
= config
.toolbar
;
12033 // Configuration initialization
12034 config
= config
|| {};
12036 // Parent constructor
12037 OO
.ui
.MenuToolGroup
.parent
.call( this, toolbar
, config
);
12040 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
12043 this.$element
.addClass( 'oo-ui-menuToolGroup' );
12048 OO
.inheritClass( OO
.ui
.MenuToolGroup
, OO
.ui
.PopupToolGroup
);
12050 /* Static Properties */
12052 OO
.ui
.MenuToolGroup
.static.name
= 'menu';
12057 * Handle the toolbar state being updated.
12059 * When the state changes, the title of each active item in the menu will be joined together and
12060 * used as a label for the group. The label will be empty if none of the items are active.
12064 OO
.ui
.MenuToolGroup
.prototype.onUpdateState = function () {
12068 for ( name
in this.tools
) {
12069 if ( this.tools
[ name
].isActive() ) {
12070 labelTexts
.push( this.tools
[ name
].getTitle() );
12074 this.setLabel( labelTexts
.join( ', ' ) || ' ' );
12078 * Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. Each popup tool is configured
12079 * 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
12080 * an #onSelect or #onUpdateState method, as these methods have been implemented already.
12082 * // Example of a popup tool. When selected, a popup tool displays
12083 * // a popup window.
12084 * function HelpTool( toolGroup, config ) {
12085 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
12090 * this.popup.$body.append( '<p>I am helpful!</p>' );
12092 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
12093 * HelpTool.static.name = 'help';
12094 * HelpTool.static.icon = 'help';
12095 * HelpTool.static.title = 'Help';
12096 * toolFactory.register( HelpTool );
12098 * For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. For more information about
12099 * toolbars in genreral, please see the [OOjs UI documentation on MediaWiki][1].
12101 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
12105 * @extends OO.ui.Tool
12106 * @mixins OO.ui.mixin.PopupElement
12109 * @param {OO.ui.ToolGroup} toolGroup
12110 * @param {Object} [config] Configuration options
12112 OO
.ui
.PopupTool
= function OoUiPopupTool( toolGroup
, config
) {
12113 // Allow passing positional parameters inside the config object
12114 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
12115 config
= toolGroup
;
12116 toolGroup
= config
.toolGroup
;
12119 // Parent constructor
12120 OO
.ui
.PopupTool
.parent
.call( this, toolGroup
, config
);
12122 // Mixin constructors
12123 OO
.ui
.mixin
.PopupElement
.call( this, config
);
12127 .addClass( 'oo-ui-popupTool' )
12128 .append( this.popup
.$element
);
12133 OO
.inheritClass( OO
.ui
.PopupTool
, OO
.ui
.Tool
);
12134 OO
.mixinClass( OO
.ui
.PopupTool
, OO
.ui
.mixin
.PopupElement
);
12139 * Handle the tool being selected.
12143 OO
.ui
.PopupTool
.prototype.onSelect = function () {
12144 if ( !this.isDisabled() ) {
12145 this.popup
.toggle();
12147 this.setActive( false );
12152 * Handle the toolbar state being updated.
12156 OO
.ui
.PopupTool
.prototype.onUpdateState = function () {
12157 this.setActive( false );
12161 * A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools}
12162 * and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used
12163 * inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from
12164 * the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list}
12165 * when the ToolGroupTool is selected.
12167 * // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', defined elsewhere.
12169 * function SettingsTool() {
12170 * SettingsTool.parent.apply( this, arguments );
12172 * OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool );
12173 * SettingsTool.static.name = 'settings';
12174 * SettingsTool.static.title = 'Change settings';
12175 * SettingsTool.static.groupConfig = {
12176 * icon: 'settings',
12177 * label: 'ToolGroupTool',
12178 * include: [ 'setting1', 'setting2' ]
12180 * toolFactory.register( SettingsTool );
12182 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
12184 * Please note that this implementation is subject to change per [T74159] [2].
12186 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars#ToolGroupTool
12187 * [2]: https://phabricator.wikimedia.org/T74159
12191 * @extends OO.ui.Tool
12194 * @param {OO.ui.ToolGroup} toolGroup
12195 * @param {Object} [config] Configuration options
12197 OO
.ui
.ToolGroupTool
= function OoUiToolGroupTool( toolGroup
, config
) {
12198 // Allow passing positional parameters inside the config object
12199 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
12200 config
= toolGroup
;
12201 toolGroup
= config
.toolGroup
;
12204 // Parent constructor
12205 OO
.ui
.ToolGroupTool
.parent
.call( this, toolGroup
, config
);
12208 this.innerToolGroup
= this.createGroup( this.constructor.static.groupConfig
);
12211 this.innerToolGroup
.connect( this, { disable
: 'onToolGroupDisable' } );
12214 this.$link
.remove();
12216 .addClass( 'oo-ui-toolGroupTool' )
12217 .append( this.innerToolGroup
.$element
);
12222 OO
.inheritClass( OO
.ui
.ToolGroupTool
, OO
.ui
.Tool
);
12224 /* Static Properties */
12227 * Toolgroup configuration.
12229 * The toolgroup configuration consists of the tools to include, as well as an icon and label
12230 * to use for the bar item. Tools can be included by symbolic name, group, or with the
12231 * wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information.
12233 * @property {Object.<string,Array>}
12235 OO
.ui
.ToolGroupTool
.static.groupConfig
= {};
12240 * Handle the tool being selected.
12244 OO
.ui
.ToolGroupTool
.prototype.onSelect = function () {
12245 this.innerToolGroup
.setActive( !this.innerToolGroup
.active
);
12250 * Synchronize disabledness state of the tool with the inner toolgroup.
12253 * @param {boolean} disabled Element is disabled
12255 OO
.ui
.ToolGroupTool
.prototype.onToolGroupDisable = function ( disabled
) {
12256 this.setDisabled( disabled
);
12260 * Handle the toolbar state being updated.
12264 OO
.ui
.ToolGroupTool
.prototype.onUpdateState = function () {
12265 this.setActive( false );
12269 * Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration.
12271 * @param {Object.<string,Array>} group Toolgroup configuration. Please see {@link OO.ui.ToolGroup toolgroup} for
12272 * more information.
12273 * @return {OO.ui.ListToolGroup}
12275 OO
.ui
.ToolGroupTool
.prototype.createGroup = function ( group
) {
12276 if ( group
.include
=== '*' ) {
12277 // Apply defaults to catch-all groups
12278 if ( group
.label
=== undefined ) {
12279 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
12283 return this.toolbar
.getToolGroupFactory().create( 'list', this.toolbar
, group
);
12287 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
12289 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
12294 * @extends OO.ui.mixin.GroupElement
12297 * @param {Object} [config] Configuration options
12299 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
12300 // Parent constructor
12301 OO
.ui
.mixin
.GroupWidget
.parent
.call( this, config
);
12306 OO
.inheritClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
12311 * Set the disabled state of the widget.
12313 * This will also update the disabled state of child widgets.
12315 * @param {boolean} disabled Disable widget
12318 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
12322 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
12323 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
12325 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
12326 if ( this.items
) {
12327 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
12328 this.items
[ i
].updateDisabled();
12336 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
12338 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
12339 * allows bidirectional communication.
12341 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
12349 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
12356 * Check if widget is disabled.
12358 * Checks parent if present, making disabled state inheritable.
12360 * @return {boolean} Widget is disabled
12362 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
12363 return this.disabled
||
12364 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
12368 * Set group element is in.
12370 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
12373 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
12375 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
12376 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
12378 // Initialize item disabled states
12379 this.updateDisabled();
12385 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
12386 * Controls include moving items up and down, removing items, and adding different kinds of items.
12388 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
12391 * @extends OO.ui.Widget
12392 * @mixins OO.ui.mixin.GroupElement
12393 * @mixins OO.ui.mixin.IconElement
12396 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
12397 * @param {Object} [config] Configuration options
12398 * @cfg {Object} [abilities] List of abilties
12399 * @cfg {boolean} [abilities.move=true] Allow moving movable items
12400 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
12402 OO
.ui
.OutlineControlsWidget
= function OoUiOutlineControlsWidget( outline
, config
) {
12403 // Allow passing positional parameters inside the config object
12404 if ( OO
.isPlainObject( outline
) && config
=== undefined ) {
12406 outline
= config
.outline
;
12409 // Configuration initialization
12410 config
= $.extend( { icon
: 'add' }, config
);
12412 // Parent constructor
12413 OO
.ui
.OutlineControlsWidget
.parent
.call( this, config
);
12415 // Mixin constructors
12416 OO
.ui
.mixin
.GroupElement
.call( this, config
);
12417 OO
.ui
.mixin
.IconElement
.call( this, config
);
12420 this.outline
= outline
;
12421 this.$movers
= $( '<div>' );
12422 this.upButton
= new OO
.ui
.ButtonWidget( {
12425 title
: OO
.ui
.msg( 'ooui-outline-control-move-up' )
12427 this.downButton
= new OO
.ui
.ButtonWidget( {
12430 title
: OO
.ui
.msg( 'ooui-outline-control-move-down' )
12432 this.removeButton
= new OO
.ui
.ButtonWidget( {
12435 title
: OO
.ui
.msg( 'ooui-outline-control-remove' )
12437 this.abilities
= { move: true, remove
: true };
12440 outline
.connect( this, {
12441 select
: 'onOutlineChange',
12442 add
: 'onOutlineChange',
12443 remove
: 'onOutlineChange'
12445 this.upButton
.connect( this, { click
: [ 'emit', 'move', -1 ] } );
12446 this.downButton
.connect( this, { click
: [ 'emit', 'move', 1 ] } );
12447 this.removeButton
.connect( this, { click
: [ 'emit', 'remove' ] } );
12450 this.$element
.addClass( 'oo-ui-outlineControlsWidget' );
12451 this.$group
.addClass( 'oo-ui-outlineControlsWidget-items' );
12453 .addClass( 'oo-ui-outlineControlsWidget-movers' )
12454 .append( this.removeButton
.$element
, this.upButton
.$element
, this.downButton
.$element
);
12455 this.$element
.append( this.$icon
, this.$group
, this.$movers
);
12456 this.setAbilities( config
.abilities
|| {} );
12461 OO
.inheritClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.Widget
);
12462 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.mixin
.GroupElement
);
12463 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.mixin
.IconElement
);
12469 * @param {number} places Number of places to move
12481 * @param {Object} abilities List of abilties
12482 * @param {boolean} [abilities.move] Allow moving movable items
12483 * @param {boolean} [abilities.remove] Allow removing removable items
12485 OO
.ui
.OutlineControlsWidget
.prototype.setAbilities = function ( abilities
) {
12488 for ( ability
in this.abilities
) {
12489 if ( abilities
[ ability
] !== undefined ) {
12490 this.abilities
[ ability
] = !!abilities
[ ability
];
12494 this.onOutlineChange();
12499 * Handle outline change events.
12501 OO
.ui
.OutlineControlsWidget
.prototype.onOutlineChange = function () {
12502 var i
, len
, firstMovable
, lastMovable
,
12503 items
= this.outline
.getItems(),
12504 selectedItem
= this.outline
.getSelectedItem(),
12505 movable
= this.abilities
.move && selectedItem
&& selectedItem
.isMovable(),
12506 removable
= this.abilities
.remove
&& selectedItem
&& selectedItem
.isRemovable();
12510 len
= items
.length
;
12511 while ( ++i
< len
) {
12512 if ( items
[ i
].isMovable() ) {
12513 firstMovable
= items
[ i
];
12519 if ( items
[ i
].isMovable() ) {
12520 lastMovable
= items
[ i
];
12525 this.upButton
.setDisabled( !movable
|| selectedItem
=== firstMovable
);
12526 this.downButton
.setDisabled( !movable
|| selectedItem
=== lastMovable
);
12527 this.removeButton
.setDisabled( !removable
);
12531 * ToggleWidget implements basic behavior of widgets with an on/off state.
12532 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
12536 * @extends OO.ui.Widget
12539 * @param {Object} [config] Configuration options
12540 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
12541 * By default, the toggle is in the 'off' state.
12543 OO
.ui
.ToggleWidget
= function OoUiToggleWidget( config
) {
12544 // Configuration initialization
12545 config
= config
|| {};
12547 // Parent constructor
12548 OO
.ui
.ToggleWidget
.parent
.call( this, config
);
12554 this.$element
.addClass( 'oo-ui-toggleWidget' );
12555 this.setValue( !!config
.value
);
12560 OO
.inheritClass( OO
.ui
.ToggleWidget
, OO
.ui
.Widget
);
12567 * A change event is emitted when the on/off state of the toggle changes.
12569 * @param {boolean} value Value representing the new state of the toggle
12575 * Get the value representing the toggle’s state.
12577 * @return {boolean} The on/off state of the toggle
12579 OO
.ui
.ToggleWidget
.prototype.getValue = function () {
12584 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
12586 * @param {boolean} value The state of the toggle
12590 OO
.ui
.ToggleWidget
.prototype.setValue = function ( value
) {
12592 if ( this.value
!== value
) {
12593 this.value
= value
;
12594 this.emit( 'change', value
);
12595 this.$element
.toggleClass( 'oo-ui-toggleWidget-on', value
);
12596 this.$element
.toggleClass( 'oo-ui-toggleWidget-off', !value
);
12597 this.$element
.attr( 'aria-checked', value
.toString() );
12603 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
12604 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
12605 * removed, and cleared from the group.
12608 * // Example: A ButtonGroupWidget with two buttons
12609 * var button1 = new OO.ui.PopupButtonWidget( {
12610 * label: 'Select a category',
12613 * $content: $( '<p>List of categories...</p>' ),
12618 * var button2 = new OO.ui.ButtonWidget( {
12619 * label: 'Add item'
12621 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
12622 * items: [button1, button2]
12624 * $( 'body' ).append( buttonGroup.$element );
12627 * @extends OO.ui.Widget
12628 * @mixins OO.ui.mixin.GroupElement
12631 * @param {Object} [config] Configuration options
12632 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
12634 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
12635 // Configuration initialization
12636 config
= config
|| {};
12638 // Parent constructor
12639 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
12641 // Mixin constructors
12642 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
12645 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
12646 if ( Array
.isArray( config
.items
) ) {
12647 this.addItems( config
.items
);
12653 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
12654 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
12657 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
12658 * feels, and functionality can be customized via the class’s configuration options
12659 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12662 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
12665 * // A button widget
12666 * var button = new OO.ui.ButtonWidget( {
12667 * label: 'Button with Icon',
12669 * iconTitle: 'Remove'
12671 * $( 'body' ).append( button.$element );
12673 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
12676 * @extends OO.ui.Widget
12677 * @mixins OO.ui.mixin.ButtonElement
12678 * @mixins OO.ui.mixin.IconElement
12679 * @mixins OO.ui.mixin.IndicatorElement
12680 * @mixins OO.ui.mixin.LabelElement
12681 * @mixins OO.ui.mixin.TitledElement
12682 * @mixins OO.ui.mixin.FlaggedElement
12683 * @mixins OO.ui.mixin.TabIndexedElement
12684 * @mixins OO.ui.mixin.AccessKeyedElement
12687 * @param {Object} [config] Configuration options
12688 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
12689 * @cfg {string} [target] The frame or window in which to open the hyperlink.
12690 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
12692 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
12693 // Configuration initialization
12694 config
= config
|| {};
12696 // Parent constructor
12697 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
12699 // Mixin constructors
12700 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
12701 OO
.ui
.mixin
.IconElement
.call( this, config
);
12702 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
12703 OO
.ui
.mixin
.LabelElement
.call( this, config
);
12704 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
12705 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
12706 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
12707 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$button
} ) );
12711 this.target
= null;
12712 this.noFollow
= false;
12715 this.connect( this, { disable
: 'onDisable' } );
12718 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
12720 .addClass( 'oo-ui-buttonWidget' )
12721 .append( this.$button
);
12722 this.setHref( config
.href
);
12723 this.setTarget( config
.target
);
12724 this.setNoFollow( config
.noFollow
);
12729 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
12730 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
12731 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
12732 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
12733 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
12734 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
12735 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
12736 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
12737 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
12744 OO
.ui
.ButtonWidget
.prototype.onMouseDown = function ( e
) {
12745 if ( !this.isDisabled() ) {
12746 // Remove the tab-index while the button is down to prevent the button from stealing focus
12747 this.$button
.removeAttr( 'tabindex' );
12750 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown
.call( this, e
);
12756 OO
.ui
.ButtonWidget
.prototype.onMouseUp = function ( e
) {
12757 if ( !this.isDisabled() ) {
12758 // Restore the tab-index after the button is up to restore the button's accessibility
12759 this.$button
.attr( 'tabindex', this.tabIndex
);
12762 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp
.call( this, e
);
12766 * Get hyperlink location.
12768 * @return {string} Hyperlink location
12770 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
12775 * Get hyperlink target.
12777 * @return {string} Hyperlink target
12779 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
12780 return this.target
;
12784 * Get search engine traversal hint.
12786 * @return {boolean} Whether search engines should avoid traversing this hyperlink
12788 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
12789 return this.noFollow
;
12793 * Set hyperlink location.
12795 * @param {string|null} href Hyperlink location, null to remove
12797 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
12798 href
= typeof href
=== 'string' ? href
: null;
12799 if ( href
!== null ) {
12800 if ( !OO
.ui
.isSafeUrl( href
) ) {
12801 throw new Error( 'Potentially unsafe href provided: ' + href
);
12806 if ( href
!== this.href
) {
12815 * Update the `href` attribute, in case of changes to href or
12821 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
12822 if ( this.href
!== null && !this.isDisabled() ) {
12823 this.$button
.attr( 'href', this.href
);
12825 this.$button
.removeAttr( 'href' );
12832 * Handle disable events.
12835 * @param {boolean} disabled Element is disabled
12837 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
12842 * Set hyperlink target.
12844 * @param {string|null} target Hyperlink target, null to remove
12846 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
12847 target
= typeof target
=== 'string' ? target
: null;
12849 if ( target
!== this.target
) {
12850 this.target
= target
;
12851 if ( target
!== null ) {
12852 this.$button
.attr( 'target', target
);
12854 this.$button
.removeAttr( 'target' );
12862 * Set search engine traversal hint.
12864 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
12866 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
12867 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
12869 if ( noFollow
!== this.noFollow
) {
12870 this.noFollow
= noFollow
;
12872 this.$button
.attr( 'rel', 'nofollow' );
12874 this.$button
.removeAttr( 'rel' );
12882 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
12883 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
12886 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
12887 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12890 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
12893 * @extends OO.ui.ButtonWidget
12894 * @mixins OO.ui.mixin.PendingElement
12897 * @param {Object} [config] Configuration options
12898 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12899 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
12900 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
12901 * for more information about setting modes.
12902 * @cfg {boolean} [framed=false] Render the action button with a frame
12904 OO
.ui
.ActionWidget
= function OoUiActionWidget( config
) {
12905 // Configuration initialization
12906 config
= $.extend( { framed
: false }, config
);
12908 // Parent constructor
12909 OO
.ui
.ActionWidget
.parent
.call( this, config
);
12911 // Mixin constructors
12912 OO
.ui
.mixin
.PendingElement
.call( this, config
);
12915 this.action
= config
.action
|| '';
12916 this.modes
= config
.modes
|| [];
12921 this.$element
.addClass( 'oo-ui-actionWidget' );
12926 OO
.inheritClass( OO
.ui
.ActionWidget
, OO
.ui
.ButtonWidget
);
12927 OO
.mixinClass( OO
.ui
.ActionWidget
, OO
.ui
.mixin
.PendingElement
);
12932 * A resize event is emitted when the size of the widget changes.
12940 * Check if the action is configured to be available in the specified `mode`.
12942 * @param {string} mode Name of mode
12943 * @return {boolean} The action is configured with the mode
12945 OO
.ui
.ActionWidget
.prototype.hasMode = function ( mode
) {
12946 return this.modes
.indexOf( mode
) !== -1;
12950 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12954 OO
.ui
.ActionWidget
.prototype.getAction = function () {
12955 return this.action
;
12959 * Get the symbolic name of the mode or modes for which the action is configured to be available.
12961 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
12962 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
12965 * @return {string[]}
12967 OO
.ui
.ActionWidget
.prototype.getModes = function () {
12968 return this.modes
.slice();
12972 * Emit a resize event if the size has changed.
12977 OO
.ui
.ActionWidget
.prototype.propagateResize = function () {
12980 if ( this.isElementAttached() ) {
12981 width
= this.$element
.width();
12982 height
= this.$element
.height();
12984 if ( width
!== this.width
|| height
!== this.height
) {
12985 this.width
= width
;
12986 this.height
= height
;
12987 this.emit( 'resize' );
12997 OO
.ui
.ActionWidget
.prototype.setIcon = function () {
12999 OO
.ui
.mixin
.IconElement
.prototype.setIcon
.apply( this, arguments
);
13000 this.propagateResize();
13008 OO
.ui
.ActionWidget
.prototype.setLabel = function () {
13010 OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.apply( this, arguments
);
13011 this.propagateResize();
13019 OO
.ui
.ActionWidget
.prototype.setFlags = function () {
13021 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags
.apply( this, arguments
);
13022 this.propagateResize();
13030 OO
.ui
.ActionWidget
.prototype.clearFlags = function () {
13032 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags
.apply( this, arguments
);
13033 this.propagateResize();
13039 * Toggle the visibility of the action button.
13041 * @param {boolean} [show] Show button, omit to toggle visibility
13044 OO
.ui
.ActionWidget
.prototype.toggle = function () {
13046 OO
.ui
.ActionWidget
.parent
.prototype.toggle
.apply( this, arguments
);
13047 this.propagateResize();
13053 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
13054 * which is used to display additional information or options.
13057 * // Example of a popup button.
13058 * var popupButton = new OO.ui.PopupButtonWidget( {
13059 * label: 'Popup button with options',
13062 * $content: $( '<p>Additional options here.</p>' ),
13064 * align: 'force-left'
13067 * // Append the button to the DOM.
13068 * $( 'body' ).append( popupButton.$element );
13071 * @extends OO.ui.ButtonWidget
13072 * @mixins OO.ui.mixin.PopupElement
13075 * @param {Object} [config] Configuration options
13077 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
13078 // Parent constructor
13079 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
13081 // Mixin constructors
13082 OO
.ui
.mixin
.PopupElement
.call( this, config
);
13085 this.connect( this, { click
: 'onAction' } );
13089 .addClass( 'oo-ui-popupButtonWidget' )
13090 .attr( 'aria-haspopup', 'true' )
13091 .append( this.popup
.$element
);
13096 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
13097 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
13102 * Handle the button action being triggered.
13106 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
13107 this.popup
.toggle();
13111 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
13112 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
13113 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
13114 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
13115 * and {@link OO.ui.mixin.LabelElement labels}. Please see
13116 * the [OOjs UI documentation][1] on MediaWiki for more information.
13119 * // Toggle buttons in the 'off' and 'on' state.
13120 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
13121 * label: 'Toggle Button off'
13123 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
13124 * label: 'Toggle Button on',
13127 * // Append the buttons to the DOM.
13128 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
13130 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
13133 * @extends OO.ui.ToggleWidget
13134 * @mixins OO.ui.mixin.ButtonElement
13135 * @mixins OO.ui.mixin.IconElement
13136 * @mixins OO.ui.mixin.IndicatorElement
13137 * @mixins OO.ui.mixin.LabelElement
13138 * @mixins OO.ui.mixin.TitledElement
13139 * @mixins OO.ui.mixin.FlaggedElement
13140 * @mixins OO.ui.mixin.TabIndexedElement
13143 * @param {Object} [config] Configuration options
13144 * @cfg {boolean} [value=false] The toggle button’s initial on/off
13145 * state. By default, the button is in the 'off' state.
13147 OO
.ui
.ToggleButtonWidget
= function OoUiToggleButtonWidget( config
) {
13148 // Configuration initialization
13149 config
= config
|| {};
13151 // Parent constructor
13152 OO
.ui
.ToggleButtonWidget
.parent
.call( this, config
);
13154 // Mixin constructors
13155 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
13156 OO
.ui
.mixin
.IconElement
.call( this, config
);
13157 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
13158 OO
.ui
.mixin
.LabelElement
.call( this, config
);
13159 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
13160 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
13161 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
13164 this.connect( this, { click
: 'onAction' } );
13167 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
13169 .addClass( 'oo-ui-toggleButtonWidget' )
13170 .append( this.$button
);
13175 OO
.inheritClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.ToggleWidget
);
13176 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
13177 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.IconElement
);
13178 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
13179 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.LabelElement
);
13180 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.TitledElement
);
13181 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
13182 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13187 * Handle the button action being triggered.
13191 OO
.ui
.ToggleButtonWidget
.prototype.onAction = function () {
13192 this.setValue( !this.value
);
13198 OO
.ui
.ToggleButtonWidget
.prototype.setValue = function ( value
) {
13200 if ( value
!== this.value
) {
13201 // Might be called from parent constructor before ButtonElement constructor
13202 if ( this.$button
) {
13203 this.$button
.attr( 'aria-pressed', value
.toString() );
13205 this.setActive( value
);
13209 OO
.ui
.ToggleButtonWidget
.parent
.prototype.setValue
.call( this, value
);
13217 OO
.ui
.ToggleButtonWidget
.prototype.setButtonElement = function ( $button
) {
13218 if ( this.$button
) {
13219 this.$button
.removeAttr( 'aria-pressed' );
13221 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement
.call( this, $button
);
13222 this.$button
.attr( 'aria-pressed', this.value
.toString() );
13226 * CapsuleMultiSelectWidgets are something like a {@link OO.ui.ComboBoxWidget combo box widget}
13227 * that allows for selecting multiple values.
13229 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
13232 * // Example: A CapsuleMultiSelectWidget.
13233 * var capsule = new OO.ui.CapsuleMultiSelectWidget( {
13234 * label: 'CapsuleMultiSelectWidget',
13235 * selected: [ 'Option 1', 'Option 3' ],
13238 * new OO.ui.MenuOptionWidget( {
13239 * data: 'Option 1',
13240 * label: 'Option One'
13242 * new OO.ui.MenuOptionWidget( {
13243 * data: 'Option 2',
13244 * label: 'Option Two'
13246 * new OO.ui.MenuOptionWidget( {
13247 * data: 'Option 3',
13248 * label: 'Option Three'
13250 * new OO.ui.MenuOptionWidget( {
13251 * data: 'Option 4',
13252 * label: 'Option Four'
13254 * new OO.ui.MenuOptionWidget( {
13255 * data: 'Option 5',
13256 * label: 'Option Five'
13261 * $( 'body' ).append( capsule.$element );
13263 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13266 * @extends OO.ui.Widget
13267 * @mixins OO.ui.mixin.TabIndexedElement
13268 * @mixins OO.ui.mixin.GroupElement
13271 * @param {Object} [config] Configuration options
13272 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
13273 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
13274 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
13275 * If specified, this popup will be shown instead of the menu (but the menu
13276 * will still be used for item labels and allowArbitrary=false). The widgets
13277 * in the popup should use this.addItemsFromData() or this.addItems() as necessary.
13278 * @cfg {jQuery} [$overlay] Render the menu or popup into a separate layer.
13279 * This configuration is useful in cases where the expanded menu is larger than
13280 * its containing `<div>`. The specified overlay layer is usually on top of
13281 * the containing `<div>` and has a larger area. By default, the menu uses
13282 * relative positioning.
13284 OO
.ui
.CapsuleMultiSelectWidget
= function OoUiCapsuleMultiSelectWidget( config
) {
13287 // Configuration initialization
13288 config
= config
|| {};
13290 // Parent constructor
13291 OO
.ui
.CapsuleMultiSelectWidget
.parent
.call( this, config
);
13293 // Properties (must be set before mixin constructor calls)
13294 this.$input
= config
.popup
? null : $( '<input>' );
13295 this.$handle
= $( '<div>' );
13297 // Mixin constructors
13298 OO
.ui
.mixin
.GroupElement
.call( this, config
);
13299 if ( config
.popup
) {
13300 config
.popup
= $.extend( {}, config
.popup
, {
13304 OO
.ui
.mixin
.PopupElement
.call( this, config
);
13305 $tabFocus
= $( '<span>' );
13306 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: $tabFocus
} ) );
13310 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
13312 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
13313 OO
.ui
.mixin
.IconElement
.call( this, config
);
13316 this.allowArbitrary
= !!config
.allowArbitrary
;
13317 this.$overlay
= config
.$overlay
|| this.$element
;
13318 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
13321 $input
: this.$input
,
13322 $container
: this.$element
,
13323 filterFromInput
: true,
13324 disabled
: this.isDisabled()
13330 if ( this.popup
) {
13332 focus
: this.onFocusForPopup
.bind( this )
13334 this.popup
.$element
.on( 'focusout', this.onPopupFocusOut
.bind( this ) );
13335 if ( this.popup
.$autoCloseIgnore
) {
13336 this.popup
.$autoCloseIgnore
.on( 'focusout', this.onPopupFocusOut
.bind( this ) );
13338 this.popup
.connect( this, {
13339 toggle: function ( visible
) {
13340 $tabFocus
.toggle( !visible
);
13345 focus
: this.onInputFocus
.bind( this ),
13346 blur
: this.onInputBlur
.bind( this ),
13347 'propertychange change click mouseup keydown keyup input cut paste select': this.onInputChange
.bind( this ),
13348 keydown
: this.onKeyDown
.bind( this ),
13349 keypress
: this.onKeyPress
.bind( this )
13352 this.menu
.connect( this, {
13353 choose
: 'onMenuChoose',
13354 add
: 'onMenuItemsChange',
13355 remove
: 'onMenuItemsChange'
13358 click
: this.onClick
.bind( this )
13362 if ( this.$input
) {
13363 this.$input
.prop( 'disabled', this.isDisabled() );
13364 this.$input
.attr( {
13366 'aria-autocomplete': 'list'
13368 this.$input
.width( '1em' );
13370 if ( config
.data
) {
13371 this.setItemsFromData( config
.data
);
13373 this.$group
.addClass( 'oo-ui-capsuleMultiSelectWidget-group' );
13374 this.$handle
.addClass( 'oo-ui-capsuleMultiSelectWidget-handle' )
13375 .append( this.$indicator
, this.$icon
, this.$group
);
13376 this.$element
.addClass( 'oo-ui-capsuleMultiSelectWidget' )
13377 .append( this.$handle
);
13378 if ( this.popup
) {
13379 this.$handle
.append( $tabFocus
);
13380 this.$overlay
.append( this.popup
.$element
);
13382 this.$handle
.append( this.$input
);
13383 this.$overlay
.append( this.menu
.$element
);
13385 this.onMenuItemsChange();
13390 OO
.inheritClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.Widget
);
13391 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.GroupElement
);
13392 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.PopupElement
);
13393 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13394 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.IndicatorElement
);
13395 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.IconElement
);
13402 * A change event is emitted when the set of selected items changes.
13404 * @param {Mixed[]} datas Data of the now-selected items
13410 * Construct a OO.ui.CapsuleItemWidget (or a subclass thereof) from given label and data.
13413 * @param {Mixed} data Custom data of any type.
13414 * @param {string} label The label text.
13415 * @return {OO.ui.CapsuleItemWidget}
13417 OO
.ui
.CapsuleMultiSelectWidget
.prototype.createItemWidget = function ( data
, label
) {
13418 return new OO
.ui
.CapsuleItemWidget( { data
: data
, label
: label
} );
13422 * Get the data of the items in the capsule
13423 * @return {Mixed[]}
13425 OO
.ui
.CapsuleMultiSelectWidget
.prototype.getItemsData = function () {
13426 return $.map( this.getItems(), function ( e
) { return e
.data
; } );
13430 * Set the items in the capsule by providing data
13432 * @param {Mixed[]} datas
13433 * @return {OO.ui.CapsuleMultiSelectWidget}
13435 OO
.ui
.CapsuleMultiSelectWidget
.prototype.setItemsFromData = function ( datas
) {
13438 items
= this.getItems();
13440 $.each( datas
, function ( i
, data
) {
13442 item
= menu
.getItemFromData( data
);
13445 label
= item
.label
;
13446 } else if ( widget
.allowArbitrary
) {
13447 label
= String( data
);
13453 for ( j
= 0; j
< items
.length
; j
++ ) {
13454 if ( items
[ j
].data
=== data
&& items
[ j
].label
=== label
) {
13456 items
.splice( j
, 1 );
13461 item
= widget
.createItemWidget( data
, label
);
13463 widget
.addItems( [ item
], i
);
13466 if ( items
.length
) {
13467 widget
.removeItems( items
);
13474 * Add items to the capsule by providing their data
13476 * @param {Mixed[]} datas
13477 * @return {OO.ui.CapsuleMultiSelectWidget}
13479 OO
.ui
.CapsuleMultiSelectWidget
.prototype.addItemsFromData = function ( datas
) {
13484 $.each( datas
, function ( i
, data
) {
13487 if ( !widget
.getItemFromData( data
) ) {
13488 item
= menu
.getItemFromData( data
);
13490 items
.push( widget
.createItemWidget( data
, item
.label
) );
13491 } else if ( widget
.allowArbitrary
) {
13492 items
.push( widget
.createItemWidget( data
, String( data
) ) );
13497 if ( items
.length
) {
13498 this.addItems( items
);
13505 * Remove items by data
13507 * @param {Mixed[]} datas
13508 * @return {OO.ui.CapsuleMultiSelectWidget}
13510 OO
.ui
.CapsuleMultiSelectWidget
.prototype.removeItemsFromData = function ( datas
) {
13514 $.each( datas
, function ( i
, data
) {
13515 var item
= widget
.getItemFromData( data
);
13517 items
.push( item
);
13521 if ( items
.length
) {
13522 this.removeItems( items
);
13531 OO
.ui
.CapsuleMultiSelectWidget
.prototype.addItems = function ( items
) {
13533 oldItems
= this.items
.slice();
13535 OO
.ui
.mixin
.GroupElement
.prototype.addItems
.call( this, items
);
13537 if ( this.items
.length
!== oldItems
.length
) {
13541 for ( i
= 0, l
= oldItems
.length
; same
&& i
< l
; i
++ ) {
13542 same
= same
&& this.items
[ i
] === oldItems
[ i
];
13546 this.emit( 'change', this.getItemsData() );
13555 OO
.ui
.CapsuleMultiSelectWidget
.prototype.removeItems = function ( items
) {
13557 oldItems
= this.items
.slice();
13559 OO
.ui
.mixin
.GroupElement
.prototype.removeItems
.call( this, items
);
13561 if ( this.items
.length
!== oldItems
.length
) {
13565 for ( i
= 0, l
= oldItems
.length
; same
&& i
< l
; i
++ ) {
13566 same
= same
&& this.items
[ i
] === oldItems
[ i
];
13570 this.emit( 'change', this.getItemsData() );
13579 OO
.ui
.CapsuleMultiSelectWidget
.prototype.clearItems = function () {
13580 if ( this.items
.length
) {
13581 OO
.ui
.mixin
.GroupElement
.prototype.clearItems
.call( this );
13582 this.emit( 'change', this.getItemsData() );
13588 * Get the capsule widget's menu.
13589 * @return {OO.ui.MenuSelectWidget} Menu widget
13591 OO
.ui
.CapsuleMultiSelectWidget
.prototype.getMenu = function () {
13596 * Handle focus events
13599 * @param {jQuery.Event} event
13601 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onInputFocus = function () {
13602 if ( !this.isDisabled() ) {
13603 this.menu
.toggle( true );
13608 * Handle blur events
13611 * @param {jQuery.Event} event
13613 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onInputBlur = function () {
13614 if ( this.allowArbitrary
&& this.$input
.val().trim() !== '' ) {
13615 this.addItemsFromData( [ this.$input
.val() ] );
13621 * Handle focus events
13624 * @param {jQuery.Event} event
13626 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onFocusForPopup = function () {
13627 if ( !this.isDisabled() ) {
13628 this.popup
.setSize( this.$handle
.width() );
13629 this.popup
.toggle( true );
13630 this.popup
.$element
.find( '*' )
13631 .filter( function () { return OO
.ui
.isFocusableElement( $( this ), true ); } )
13638 * Handles popup focus out events.
13641 * @param {Event} e Focus out event
13643 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onPopupFocusOut = function () {
13644 var widget
= this.popup
;
13646 setTimeout( function () {
13648 widget
.isVisible() &&
13649 !OO
.ui
.contains( widget
.$element
[ 0 ], document
.activeElement
, true ) &&
13650 ( !widget
.$autoCloseIgnore
|| !widget
.$autoCloseIgnore
.has( document
.activeElement
).length
)
13652 widget
.toggle( false );
13658 * Handle mouse click events.
13661 * @param {jQuery.Event} e Mouse click event
13663 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onClick = function ( e
) {
13664 if ( e
.which
=== 1 ) {
13671 * Handle key press events.
13674 * @param {jQuery.Event} e Key press event
13676 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onKeyPress = function ( e
) {
13679 if ( !this.isDisabled() ) {
13680 if ( e
.which
=== OO
.ui
.Keys
.ESCAPE
) {
13685 if ( !this.popup
) {
13686 this.menu
.toggle( true );
13687 if ( e
.which
=== OO
.ui
.Keys
.ENTER
) {
13688 item
= this.menu
.getItemFromLabel( this.$input
.val(), true );
13690 this.addItemsFromData( [ item
.data
] );
13692 } else if ( this.allowArbitrary
&& this.$input
.val().trim() !== '' ) {
13693 this.addItemsFromData( [ this.$input
.val() ] );
13699 // Make sure the input gets resized.
13700 setTimeout( this.onInputChange
.bind( this ), 0 );
13706 * Handle key down events.
13709 * @param {jQuery.Event} e Key down event
13711 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onKeyDown = function ( e
) {
13712 if ( !this.isDisabled() ) {
13713 // 'keypress' event is not triggered for Backspace
13714 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.$input
.val() === '' ) {
13715 if ( this.items
.length
) {
13716 this.removeItems( this.items
.slice( -1 ) );
13724 * Handle input change events.
13727 * @param {jQuery.Event} e Event of some sort
13729 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onInputChange = function () {
13730 if ( !this.isDisabled() ) {
13731 this.$input
.width( this.$input
.val().length
+ 'em' );
13736 * Handle menu choose events.
13739 * @param {OO.ui.OptionWidget} item Chosen item
13741 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onMenuChoose = function ( item
) {
13742 if ( item
&& item
.isVisible() ) {
13743 this.addItemsFromData( [ item
.getData() ] );
13749 * Handle menu item change events.
13753 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onMenuItemsChange = function () {
13754 this.setItemsFromData( this.getItemsData() );
13755 this.$element
.toggleClass( 'oo-ui-capsuleMultiSelectWidget-empty', this.menu
.isEmpty() );
13759 * Clear the input field
13762 OO
.ui
.CapsuleMultiSelectWidget
.prototype.clearInput = function () {
13763 if ( this.$input
) {
13764 this.$input
.val( '' );
13765 this.$input
.width( '1em' );
13767 if ( this.popup
) {
13768 this.popup
.toggle( false );
13770 this.menu
.toggle( false );
13771 this.menu
.selectItem();
13772 this.menu
.highlightItem();
13778 OO
.ui
.CapsuleMultiSelectWidget
.prototype.setDisabled = function ( disabled
) {
13782 OO
.ui
.CapsuleMultiSelectWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
13784 if ( this.$input
) {
13785 this.$input
.prop( 'disabled', this.isDisabled() );
13788 this.menu
.setDisabled( this.isDisabled() );
13790 if ( this.popup
) {
13791 this.popup
.setDisabled( this.isDisabled() );
13794 if ( this.items
) {
13795 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
13796 this.items
[ i
].updateDisabled();
13806 * @return {OO.ui.CapsuleMultiSelectWidget}
13808 OO
.ui
.CapsuleMultiSelectWidget
.prototype.focus = function () {
13809 if ( !this.isDisabled() ) {
13810 if ( this.popup
) {
13811 this.popup
.setSize( this.$handle
.width() );
13812 this.popup
.toggle( true );
13813 this.popup
.$element
.find( '*' )
13814 .filter( function () { return OO
.ui
.isFocusableElement( $( this ), true ); } )
13818 this.menu
.toggle( true );
13819 this.$input
.focus();
13826 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiSelectWidget
13827 * CapsuleMultiSelectWidget} to display the selected items.
13830 * @extends OO.ui.Widget
13831 * @mixins OO.ui.mixin.ItemWidget
13832 * @mixins OO.ui.mixin.IndicatorElement
13833 * @mixins OO.ui.mixin.LabelElement
13834 * @mixins OO.ui.mixin.FlaggedElement
13835 * @mixins OO.ui.mixin.TabIndexedElement
13838 * @param {Object} [config] Configuration options
13840 OO
.ui
.CapsuleItemWidget
= function OoUiCapsuleItemWidget( config
) {
13841 // Configuration initialization
13842 config
= config
|| {};
13844 // Parent constructor
13845 OO
.ui
.CapsuleItemWidget
.parent
.call( this, config
);
13847 // Properties (must be set before mixin constructor calls)
13848 this.$indicator
= $( '<span>' );
13850 // Mixin constructors
13851 OO
.ui
.mixin
.ItemWidget
.call( this );
13852 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$indicator
, indicator
: 'clear' } ) );
13853 OO
.ui
.mixin
.LabelElement
.call( this, config
);
13854 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
13855 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$indicator
} ) );
13858 this.$indicator
.on( {
13859 keydown
: this.onCloseKeyDown
.bind( this ),
13860 click
: this.onCloseClick
.bind( this )
13865 .addClass( 'oo-ui-capsuleItemWidget' )
13866 .append( this.$indicator
, this.$label
);
13871 OO
.inheritClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.Widget
);
13872 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.ItemWidget
);
13873 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.IndicatorElement
);
13874 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.LabelElement
);
13875 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.FlaggedElement
);
13876 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13881 * Handle close icon clicks
13882 * @param {jQuery.Event} event
13884 OO
.ui
.CapsuleItemWidget
.prototype.onCloseClick = function () {
13885 var element
= this.getElementGroup();
13887 if ( !this.isDisabled() && element
&& $.isFunction( element
.removeItems
) ) {
13888 element
.removeItems( [ this ] );
13894 * Handle close keyboard events
13895 * @param {jQuery.Event} event Key down event
13897 OO
.ui
.CapsuleItemWidget
.prototype.onCloseKeyDown = function ( e
) {
13898 if ( !this.isDisabled() && $.isFunction( this.getElementGroup().removeItems
) ) {
13899 switch ( e
.which
) {
13900 case OO
.ui
.Keys
.ENTER
:
13901 case OO
.ui
.Keys
.BACKSPACE
:
13902 case OO
.ui
.Keys
.SPACE
:
13903 this.getElementGroup().removeItems( [ this ] );
13910 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
13911 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
13912 * users can interact with it.
13914 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
13915 * OO.ui.DropdownInputWidget instead.
13918 * // Example: A DropdownWidget with a menu that contains three options
13919 * var dropDown = new OO.ui.DropdownWidget( {
13920 * label: 'Dropdown menu: Select a menu option',
13923 * new OO.ui.MenuOptionWidget( {
13927 * new OO.ui.MenuOptionWidget( {
13931 * new OO.ui.MenuOptionWidget( {
13939 * $( 'body' ).append( dropDown.$element );
13941 * dropDown.getMenu().selectItemByData( 'b' );
13943 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
13945 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
13947 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13950 * @extends OO.ui.Widget
13951 * @mixins OO.ui.mixin.IconElement
13952 * @mixins OO.ui.mixin.IndicatorElement
13953 * @mixins OO.ui.mixin.LabelElement
13954 * @mixins OO.ui.mixin.TitledElement
13955 * @mixins OO.ui.mixin.TabIndexedElement
13958 * @param {Object} [config] Configuration options
13959 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
13960 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
13961 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
13962 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
13964 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
13965 // Configuration initialization
13966 config
= $.extend( { indicator
: 'down' }, config
);
13968 // Parent constructor
13969 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
13971 // Properties (must be set before TabIndexedElement constructor call)
13972 this.$handle
= this.$( '<span>' );
13973 this.$overlay
= config
.$overlay
|| this.$element
;
13975 // Mixin constructors
13976 OO
.ui
.mixin
.IconElement
.call( this, config
);
13977 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
13978 OO
.ui
.mixin
.LabelElement
.call( this, config
);
13979 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
13980 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
13983 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend( {
13985 $container
: this.$element
13986 }, config
.menu
) );
13990 click
: this.onClick
.bind( this ),
13991 keypress
: this.onKeyPress
.bind( this )
13993 this.menu
.connect( this, { select
: 'onMenuSelect' } );
13997 .addClass( 'oo-ui-dropdownWidget-handle' )
13998 .append( this.$icon
, this.$label
, this.$indicator
);
14000 .addClass( 'oo-ui-dropdownWidget' )
14001 .append( this.$handle
);
14002 this.$overlay
.append( this.menu
.$element
);
14007 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
14008 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
14009 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
14010 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
14011 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
14012 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
14019 * @return {OO.ui.MenuSelectWidget} Menu of widget
14021 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
14026 * Handles menu select events.
14029 * @param {OO.ui.MenuOptionWidget} item Selected menu item
14031 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
14035 this.setLabel( null );
14039 selectedLabel
= item
.getLabel();
14041 // If the label is a DOM element, clone it, because setLabel will append() it
14042 if ( selectedLabel
instanceof jQuery
) {
14043 selectedLabel
= selectedLabel
.clone();
14046 this.setLabel( selectedLabel
);
14050 * Handle mouse click events.
14053 * @param {jQuery.Event} e Mouse click event
14055 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
14056 if ( !this.isDisabled() && e
.which
=== 1 ) {
14057 this.menu
.toggle();
14063 * Handle key press events.
14066 * @param {jQuery.Event} e Key press event
14068 OO
.ui
.DropdownWidget
.prototype.onKeyPress = function ( e
) {
14069 if ( !this.isDisabled() &&
14070 ( ( e
.which
=== OO
.ui
.Keys
.SPACE
&& !this.menu
.isVisible() ) || e
.which
=== OO
.ui
.Keys
.ENTER
)
14072 this.menu
.toggle();
14078 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
14079 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
14080 * OO.ui.mixin.IndicatorElement indicators}.
14081 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14084 * // Example of a file select widget
14085 * var selectFile = new OO.ui.SelectFileWidget();
14086 * $( 'body' ).append( selectFile.$element );
14088 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
14091 * @extends OO.ui.Widget
14092 * @mixins OO.ui.mixin.IconElement
14093 * @mixins OO.ui.mixin.IndicatorElement
14094 * @mixins OO.ui.mixin.PendingElement
14095 * @mixins OO.ui.mixin.LabelElement
14098 * @param {Object} [config] Configuration options
14099 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
14100 * @cfg {string} [placeholder] Text to display when no file is selected.
14101 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
14102 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
14103 * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
14104 * @cfg {boolean} [dragDropUI=false] Deprecated alias for showDropTarget
14106 OO
.ui
.SelectFileWidget
= function OoUiSelectFileWidget( config
) {
14109 // TODO: Remove in next release
14110 if ( config
&& config
.dragDropUI
) {
14111 config
.showDropTarget
= true;
14114 // Configuration initialization
14115 config
= $.extend( {
14117 placeholder
: OO
.ui
.msg( 'ooui-selectfile-placeholder' ),
14118 notsupported
: OO
.ui
.msg( 'ooui-selectfile-not-supported' ),
14120 showDropTarget
: false
14123 // Parent constructor
14124 OO
.ui
.SelectFileWidget
.parent
.call( this, config
);
14126 // Mixin constructors
14127 OO
.ui
.mixin
.IconElement
.call( this, config
);
14128 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
14129 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$info
} ) );
14130 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { autoFitLabel
: true } ) );
14133 this.$info
= $( '<span>' );
14136 this.showDropTarget
= config
.showDropTarget
;
14137 this.isSupported
= this.constructor.static.isSupported();
14138 this.currentFile
= null;
14139 if ( Array
.isArray( config
.accept
) ) {
14140 this.accept
= config
.accept
;
14142 this.accept
= null;
14144 this.placeholder
= config
.placeholder
;
14145 this.notsupported
= config
.notsupported
;
14146 this.onFileSelectedHandler
= this.onFileSelected
.bind( this );
14148 this.selectButton
= new OO
.ui
.ButtonWidget( {
14149 classes
: [ 'oo-ui-selectFileWidget-selectButton' ],
14150 label
: 'Select a file',
14151 disabled
: this.disabled
|| !this.isSupported
14154 this.clearButton
= new OO
.ui
.ButtonWidget( {
14155 classes
: [ 'oo-ui-selectFileWidget-clearButton' ],
14158 disabled
: this.disabled
14162 this.selectButton
.$button
.on( {
14163 keypress
: this.onKeyPress
.bind( this )
14165 this.clearButton
.connect( this, {
14166 click
: 'onClearClick'
14168 if ( config
.droppable
) {
14169 dragHandler
= this.onDragEnterOrOver
.bind( this );
14170 this.$element
.on( {
14171 dragenter
: dragHandler
,
14172 dragover
: dragHandler
,
14173 dragleave
: this.onDragLeave
.bind( this ),
14174 drop
: this.onDrop
.bind( this )
14181 this.$label
.addClass( 'oo-ui-selectFileWidget-label' );
14183 .addClass( 'oo-ui-selectFileWidget-info' )
14184 .append( this.$icon
, this.$label
, this.clearButton
.$element
, this.$indicator
);
14186 .addClass( 'oo-ui-selectFileWidget' )
14187 .append( this.$info
, this.selectButton
.$element
);
14188 if ( config
.droppable
&& config
.showDropTarget
) {
14189 this.$dropTarget
= $( '<div>' )
14190 .addClass( 'oo-ui-selectFileWidget-dropTarget' )
14191 .text( OO
.ui
.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
14193 click
: this.onDropTargetClick
.bind( this )
14195 this.$element
.prepend( this.$dropTarget
);
14201 OO
.inheritClass( OO
.ui
.SelectFileWidget
, OO
.ui
.Widget
);
14202 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.IconElement
);
14203 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.IndicatorElement
);
14204 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.PendingElement
);
14205 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.LabelElement
);
14207 /* Static Properties */
14210 * Check if this widget is supported
14213 * @return {boolean}
14215 OO
.ui
.SelectFileWidget
.static.isSupported = function () {
14217 if ( OO
.ui
.SelectFileWidget
.static.isSupportedCache
=== null ) {
14218 $input
= $( '<input type="file">' );
14219 OO
.ui
.SelectFileWidget
.static.isSupportedCache
= $input
[ 0 ].files
!== undefined;
14221 return OO
.ui
.SelectFileWidget
.static.isSupportedCache
;
14224 OO
.ui
.SelectFileWidget
.static.isSupportedCache
= null;
14231 * A change event is emitted when the on/off state of the toggle changes.
14233 * @param {File|null} value New value
14239 * Get the current value of the field
14241 * @return {File|null}
14243 OO
.ui
.SelectFileWidget
.prototype.getValue = function () {
14244 return this.currentFile
;
14248 * Set the current value of the field
14250 * @param {File|null} file File to select
14252 OO
.ui
.SelectFileWidget
.prototype.setValue = function ( file
) {
14253 if ( this.currentFile
!== file
) {
14254 this.currentFile
= file
;
14256 this.emit( 'change', this.currentFile
);
14261 * Focus the widget.
14263 * Focusses the select file button.
14267 OO
.ui
.SelectFileWidget
.prototype.focus = function () {
14268 this.selectButton
.$button
[ 0 ].focus();
14273 * Update the user interface when a file is selected or unselected
14277 OO
.ui
.SelectFileWidget
.prototype.updateUI = function () {
14279 if ( !this.isSupported
) {
14280 this.$element
.addClass( 'oo-ui-selectFileWidget-notsupported' );
14281 this.$element
.removeClass( 'oo-ui-selectFileWidget-empty' );
14282 this.setLabel( this.notsupported
);
14284 this.$element
.addClass( 'oo-ui-selectFileWidget-supported' );
14285 if ( this.currentFile
) {
14286 this.$element
.removeClass( 'oo-ui-selectFileWidget-empty' );
14288 if ( this.currentFile
.type
!== '' ) {
14289 $label
= $label
.add( $( '<span>' ).addClass( 'oo-ui-selectFileWidget-fileType' ).text( this.currentFile
.type
) );
14291 $label
= $label
.add( $( '<span>' ).text( this.currentFile
.name
) );
14292 this.setLabel( $label
);
14294 this.$element
.addClass( 'oo-ui-selectFileWidget-empty' );
14295 this.setLabel( this.placeholder
);
14299 if ( this.$input
) {
14300 this.$input
.attr( 'title', this.getLabel() );
14305 * Add the input to the widget
14309 OO
.ui
.SelectFileWidget
.prototype.addInput = function () {
14310 if ( this.$input
) {
14311 this.$input
.remove();
14314 if ( !this.isSupported
) {
14315 this.$input
= null;
14319 this.$input
= $( '<input type="file">' );
14320 this.$input
.on( 'change', this.onFileSelectedHandler
);
14321 this.$input
.attr( {
14323 title
: this.getLabel()
14325 if ( this.accept
) {
14326 this.$input
.attr( 'accept', this.accept
.join( ', ' ) );
14328 this.selectButton
.$button
.append( this.$input
);
14332 * Determine if we should accept this file
14335 * @param {string} File MIME type
14336 * @return {boolean}
14338 OO
.ui
.SelectFileWidget
.prototype.isAllowedType = function ( mimeType
) {
14341 if ( !this.accept
|| !mimeType
) {
14345 for ( i
= 0; i
< this.accept
.length
; i
++ ) {
14346 mimeTest
= this.accept
[ i
];
14347 if ( mimeTest
=== mimeType
) {
14349 } else if ( mimeTest
.substr( -2 ) === '/*' ) {
14350 mimeTest
= mimeTest
.substr( 0, mimeTest
.length
- 1 );
14351 if ( mimeType
.substr( 0, mimeTest
.length
) === mimeTest
) {
14361 * Handle file selection from the input
14364 * @param {jQuery.Event} e
14366 OO
.ui
.SelectFileWidget
.prototype.onFileSelected = function ( e
) {
14367 var file
= OO
.getProp( e
.target
, 'files', 0 ) || null;
14369 if ( file
&& !this.isAllowedType( file
.type
) ) {
14373 this.setValue( file
);
14378 * Handle clear button click events.
14382 OO
.ui
.SelectFileWidget
.prototype.onClearClick = function () {
14383 this.setValue( null );
14388 * Handle key press events.
14391 * @param {jQuery.Event} e Key press event
14393 OO
.ui
.SelectFileWidget
.prototype.onKeyPress = function ( e
) {
14394 if ( this.isSupported
&& !this.isDisabled() && this.$input
&&
14395 ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
14397 this.$input
.click();
14403 * Handle drop target click events.
14406 * @param {jQuery.Event} e Key press event
14408 OO
.ui
.SelectFileWidget
.prototype.onDropTargetClick = function () {
14409 if ( this.isSupported
&& !this.isDisabled() && this.$input
) {
14410 this.$input
.click();
14416 * Handle drag enter and over events
14419 * @param {jQuery.Event} e Drag event
14421 OO
.ui
.SelectFileWidget
.prototype.onDragEnterOrOver = function ( e
) {
14423 droppableFile
= false,
14424 dt
= e
.originalEvent
.dataTransfer
;
14426 e
.preventDefault();
14427 e
.stopPropagation();
14429 if ( this.isDisabled() || !this.isSupported
) {
14430 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14431 dt
.dropEffect
= 'none';
14435 // DataTransferItem and File both have a type property, but in Chrome files
14436 // have no information at this point.
14437 itemOrFile
= OO
.getProp( dt
, 'items', 0 ) || OO
.getProp( dt
, 'files', 0 );
14438 if ( itemOrFile
) {
14439 if ( this.isAllowedType( itemOrFile
.type
) ) {
14440 droppableFile
= true;
14442 // dt.types is Array-like, but not an Array
14443 } else if ( Array
.prototype.indexOf
.call( OO
.getProp( dt
, 'types' ) || [], 'Files' ) !== -1 ) {
14444 // File information is not available at this point for security so just assume
14445 // it is acceptable for now.
14446 // https://bugzilla.mozilla.org/show_bug.cgi?id=640534
14447 droppableFile
= true;
14450 this.$element
.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile
);
14451 if ( !droppableFile
) {
14452 dt
.dropEffect
= 'none';
14459 * Handle drag leave events
14462 * @param {jQuery.Event} e Drag event
14464 OO
.ui
.SelectFileWidget
.prototype.onDragLeave = function () {
14465 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14469 * Handle drop events
14472 * @param {jQuery.Event} e Drop event
14474 OO
.ui
.SelectFileWidget
.prototype.onDrop = function ( e
) {
14476 dt
= e
.originalEvent
.dataTransfer
;
14478 e
.preventDefault();
14479 e
.stopPropagation();
14480 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14482 if ( this.isDisabled() || !this.isSupported
) {
14486 file
= OO
.getProp( dt
, 'files', 0 );
14487 if ( file
&& !this.isAllowedType( file
.type
) ) {
14491 this.setValue( file
);
14500 OO
.ui
.SelectFileWidget
.prototype.setDisabled = function ( disabled
) {
14501 OO
.ui
.SelectFileWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
14502 if ( this.selectButton
) {
14503 this.selectButton
.setDisabled( disabled
);
14505 if ( this.clearButton
) {
14506 this.clearButton
.setDisabled( disabled
);
14512 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
14513 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
14514 * for a list of icons included in the library.
14517 * // An icon widget with a label
14518 * var myIcon = new OO.ui.IconWidget( {
14520 * iconTitle: 'Help'
14522 * // Create a label.
14523 * var iconLabel = new OO.ui.LabelWidget( {
14526 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
14528 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
14531 * @extends OO.ui.Widget
14532 * @mixins OO.ui.mixin.IconElement
14533 * @mixins OO.ui.mixin.TitledElement
14534 * @mixins OO.ui.mixin.FlaggedElement
14537 * @param {Object} [config] Configuration options
14539 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
14540 // Configuration initialization
14541 config
= config
|| {};
14543 // Parent constructor
14544 OO
.ui
.IconWidget
.parent
.call( this, config
);
14546 // Mixin constructors
14547 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
14548 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
14549 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
14552 this.$element
.addClass( 'oo-ui-iconWidget' );
14557 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
14558 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
14559 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
14560 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
14562 /* Static Properties */
14564 OO
.ui
.IconWidget
.static.tagName
= 'span';
14567 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
14568 * attention to the status of an item or to clarify the function of a control. For a list of
14569 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
14572 * // Example of an indicator widget
14573 * var indicator1 = new OO.ui.IndicatorWidget( {
14574 * indicator: 'alert'
14577 * // Create a fieldset layout to add a label
14578 * var fieldset = new OO.ui.FieldsetLayout();
14579 * fieldset.addItems( [
14580 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
14582 * $( 'body' ).append( fieldset.$element );
14584 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
14587 * @extends OO.ui.Widget
14588 * @mixins OO.ui.mixin.IndicatorElement
14589 * @mixins OO.ui.mixin.TitledElement
14592 * @param {Object} [config] Configuration options
14594 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
14595 // Configuration initialization
14596 config
= config
|| {};
14598 // Parent constructor
14599 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
14601 // Mixin constructors
14602 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
14603 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
14606 this.$element
.addClass( 'oo-ui-indicatorWidget' );
14611 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
14612 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
14613 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
14615 /* Static Properties */
14617 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
14620 * InputWidget is the base class for all input widgets, which
14621 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
14622 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
14623 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14625 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14629 * @extends OO.ui.Widget
14630 * @mixins OO.ui.mixin.FlaggedElement
14631 * @mixins OO.ui.mixin.TabIndexedElement
14632 * @mixins OO.ui.mixin.TitledElement
14633 * @mixins OO.ui.mixin.AccessKeyedElement
14636 * @param {Object} [config] Configuration options
14637 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
14638 * @cfg {string} [value=''] The value of the input.
14639 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
14640 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
14641 * before it is accepted.
14643 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
14644 // Configuration initialization
14645 config
= config
|| {};
14647 // Parent constructor
14648 OO
.ui
.InputWidget
.parent
.call( this, config
);
14651 this.$input
= this.getInputElement( config
);
14653 this.inputFilter
= config
.inputFilter
;
14655 // Mixin constructors
14656 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
14657 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
14658 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
14659 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$input
} ) );
14662 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
14666 .addClass( 'oo-ui-inputWidget-input' )
14667 .attr( 'name', config
.name
)
14668 .prop( 'disabled', this.isDisabled() );
14670 .addClass( 'oo-ui-inputWidget' )
14671 .append( this.$input
);
14672 this.setValue( config
.value
);
14673 this.setAccessKey( config
.accessKey
);
14674 if ( config
.dir
) {
14675 this.setDir( config
.dir
);
14681 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
14682 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
14683 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
14684 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
14685 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
14687 /* Static Properties */
14689 OO
.ui
.InputWidget
.static.supportsSimpleLabel
= true;
14691 /* Static Methods */
14696 OO
.ui
.InputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
14697 config
= OO
.ui
.InputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
14698 // Reusing $input lets browsers preserve inputted values across page reloads (T114134)
14699 config
.$input
= $( node
).find( '.oo-ui-inputWidget-input' );
14706 OO
.ui
.InputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
14707 var state
= OO
.ui
.InputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
14708 state
.value
= config
.$input
.val();
14709 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
14710 state
.focus
= config
.$input
.is( ':focus' );
14719 * A change event is emitted when the value of the input changes.
14721 * @param {string} value
14727 * Get input element.
14729 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
14730 * different circumstances. The element must have a `value` property (like form elements).
14733 * @param {Object} config Configuration options
14734 * @return {jQuery} Input element
14736 OO
.ui
.InputWidget
.prototype.getInputElement = function ( config
) {
14737 // See #reusePreInfuseDOM about config.$input
14738 return config
.$input
|| $( '<input>' );
14742 * Handle potentially value-changing events.
14745 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
14747 OO
.ui
.InputWidget
.prototype.onEdit = function () {
14749 if ( !this.isDisabled() ) {
14750 // Allow the stack to clear so the value will be updated
14751 setTimeout( function () {
14752 widget
.setValue( widget
.$input
.val() );
14758 * Get the value of the input.
14760 * @return {string} Input value
14762 OO
.ui
.InputWidget
.prototype.getValue = function () {
14763 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14764 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14765 var value
= this.$input
.val();
14766 if ( this.value
!== value
) {
14767 this.setValue( value
);
14773 * Set the directionality of the input, either RTL (right-to-left) or LTR (left-to-right).
14775 * @deprecated since v0.13.1, use #setDir directly
14776 * @param {boolean} isRTL Directionality is right-to-left
14779 OO
.ui
.InputWidget
.prototype.setRTL = function ( isRTL
) {
14780 this.setDir( isRTL
? 'rtl' : 'ltr' );
14785 * Set the directionality of the input.
14787 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
14790 OO
.ui
.InputWidget
.prototype.setDir = function ( dir
) {
14791 this.$input
.prop( 'dir', dir
);
14796 * Set the value of the input.
14798 * @param {string} value New value
14802 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
14803 value
= this.cleanUpValue( value
);
14804 // Update the DOM if it has changed. Note that with cleanUpValue, it
14805 // is possible for the DOM value to change without this.value changing.
14806 if ( this.$input
.val() !== value
) {
14807 this.$input
.val( value
);
14809 if ( this.value
!== value
) {
14810 this.value
= value
;
14811 this.emit( 'change', this.value
);
14817 * Set the input's access key.
14818 * FIXME: This is the same code as in OO.ui.mixin.ButtonElement, maybe find a better place for it?
14820 * @param {string} accessKey Input's access key, use empty string to remove
14823 OO
.ui
.InputWidget
.prototype.setAccessKey = function ( accessKey
) {
14824 accessKey
= typeof accessKey
=== 'string' && accessKey
.length
? accessKey
: null;
14826 if ( this.accessKey
!== accessKey
) {
14827 if ( this.$input
) {
14828 if ( accessKey
!== null ) {
14829 this.$input
.attr( 'accesskey', accessKey
);
14831 this.$input
.removeAttr( 'accesskey' );
14834 this.accessKey
= accessKey
;
14841 * Clean up incoming value.
14843 * Ensures value is a string, and converts undefined and null to empty string.
14846 * @param {string} value Original value
14847 * @return {string} Cleaned up value
14849 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
14850 if ( value
=== undefined || value
=== null ) {
14852 } else if ( this.inputFilter
) {
14853 return this.inputFilter( String( value
) );
14855 return String( value
);
14860 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
14861 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
14864 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
14865 if ( !this.isDisabled() ) {
14866 if ( this.$input
.is( ':checkbox, :radio' ) ) {
14867 this.$input
.click();
14869 if ( this.$input
.is( ':input' ) ) {
14870 this.$input
[ 0 ].focus();
14878 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
14879 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
14880 if ( this.$input
) {
14881 this.$input
.prop( 'disabled', this.isDisabled() );
14891 OO
.ui
.InputWidget
.prototype.focus = function () {
14892 this.$input
[ 0 ].focus();
14901 OO
.ui
.InputWidget
.prototype.blur = function () {
14902 this.$input
[ 0 ].blur();
14909 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
14910 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
14911 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
14912 this.setValue( state
.value
);
14914 if ( state
.focus
) {
14920 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
14921 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
14922 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
14923 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
14924 * [OOjs UI documentation on MediaWiki] [1] for more information.
14927 * // A ButtonInputWidget rendered as an HTML button, the default.
14928 * var button = new OO.ui.ButtonInputWidget( {
14929 * label: 'Input button',
14933 * $( 'body' ).append( button.$element );
14935 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
14938 * @extends OO.ui.InputWidget
14939 * @mixins OO.ui.mixin.ButtonElement
14940 * @mixins OO.ui.mixin.IconElement
14941 * @mixins OO.ui.mixin.IndicatorElement
14942 * @mixins OO.ui.mixin.LabelElement
14943 * @mixins OO.ui.mixin.TitledElement
14946 * @param {Object} [config] Configuration options
14947 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
14948 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
14949 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
14950 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
14951 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
14953 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
14954 // Configuration initialization
14955 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
14957 // Properties (must be set before parent constructor, which calls #setValue)
14958 this.useInputTag
= config
.useInputTag
;
14960 // Parent constructor
14961 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
14963 // Mixin constructors
14964 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
14965 OO
.ui
.mixin
.IconElement
.call( this, config
);
14966 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
14967 OO
.ui
.mixin
.LabelElement
.call( this, config
);
14968 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
14971 if ( !config
.useInputTag
) {
14972 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
14974 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
14979 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
14980 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
14981 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
14982 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
14983 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
14984 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
14986 /* Static Properties */
14989 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
14990 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
14992 OO
.ui
.ButtonInputWidget
.static.supportsSimpleLabel
= false;
15000 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
15002 // See InputWidget#reusePreInfuseDOM about config.$input
15003 if ( config
.$input
) {
15004 return config
.$input
.empty();
15006 type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ? config
.type
: 'button';
15007 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
15013 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
15015 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
15016 * text, or `null` for no label
15019 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
15020 OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
15022 if ( this.useInputTag
) {
15023 if ( typeof label
=== 'function' ) {
15024 label
= OO
.ui
.resolveMsg( label
);
15026 if ( label
instanceof jQuery
) {
15027 label
= label
.text();
15032 this.$input
.val( label
);
15039 * Set the value of the input.
15041 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
15042 * they do not support {@link #value values}.
15044 * @param {string} value New value
15047 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
15048 if ( !this.useInputTag
) {
15049 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
15055 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
15056 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
15057 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
15058 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
15060 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15063 * // An example of selected, unselected, and disabled checkbox inputs
15064 * var checkbox1=new OO.ui.CheckboxInputWidget( {
15068 * var checkbox2=new OO.ui.CheckboxInputWidget( {
15071 * var checkbox3=new OO.ui.CheckboxInputWidget( {
15075 * // Create a fieldset layout with fields for each checkbox.
15076 * var fieldset = new OO.ui.FieldsetLayout( {
15077 * label: 'Checkboxes'
15079 * fieldset.addItems( [
15080 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
15081 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
15082 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
15084 * $( 'body' ).append( fieldset.$element );
15086 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15089 * @extends OO.ui.InputWidget
15092 * @param {Object} [config] Configuration options
15093 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
15095 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
15096 // Configuration initialization
15097 config
= config
|| {};
15099 // Parent constructor
15100 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
15104 .addClass( 'oo-ui-checkboxInputWidget' )
15105 // Required for pretty styling in MediaWiki theme
15106 .append( $( '<span>' ) );
15107 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
15112 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
15114 /* Static Methods */
15119 OO
.ui
.CheckboxInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
15120 var state
= OO
.ui
.CheckboxInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
15121 state
.checked
= config
.$input
.prop( 'checked' );
15131 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
15132 return $( '<input type="checkbox" />' );
15138 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
15140 if ( !this.isDisabled() ) {
15141 // Allow the stack to clear so the value will be updated
15142 setTimeout( function () {
15143 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
15149 * Set selection state of this checkbox.
15151 * @param {boolean} state `true` for selected
15154 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
15156 if ( this.selected
!== state
) {
15157 this.selected
= state
;
15158 this.$input
.prop( 'checked', this.selected
);
15159 this.emit( 'change', this.selected
);
15165 * Check if this checkbox is selected.
15167 * @return {boolean} Checkbox is selected
15169 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
15170 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
15171 // it, and we won't know unless they're kind enough to trigger a 'change' event.
15172 var selected
= this.$input
.prop( 'checked' );
15173 if ( this.selected
!== selected
) {
15174 this.setSelected( selected
);
15176 return this.selected
;
15182 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
15183 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
15184 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
15185 this.setSelected( state
.checked
);
15190 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
15191 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15192 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15193 * more information about input widgets.
15195 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
15196 * are no options. If no `value` configuration option is provided, the first option is selected.
15197 * If you need a state representing no value (no option being selected), use a DropdownWidget.
15199 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
15202 * // Example: A DropdownInputWidget with three options
15203 * var dropdownInput = new OO.ui.DropdownInputWidget( {
15205 * { data: 'a', label: 'First' },
15206 * { data: 'b', label: 'Second'},
15207 * { data: 'c', label: 'Third' }
15210 * $( 'body' ).append( dropdownInput.$element );
15212 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15215 * @extends OO.ui.InputWidget
15216 * @mixins OO.ui.mixin.TitledElement
15219 * @param {Object} [config] Configuration options
15220 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15221 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
15223 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
15224 // Configuration initialization
15225 config
= config
|| {};
15227 // Properties (must be done before parent constructor which calls #setDisabled)
15228 this.dropdownWidget
= new OO
.ui
.DropdownWidget( config
.dropdown
);
15230 // Parent constructor
15231 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
15233 // Mixin constructors
15234 OO
.ui
.mixin
.TitledElement
.call( this, config
);
15237 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
15240 this.setOptions( config
.options
|| [] );
15242 .addClass( 'oo-ui-dropdownInputWidget' )
15243 .append( this.dropdownWidget
.$element
);
15248 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
15249 OO
.mixinClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.mixin
.TitledElement
);
15257 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function ( config
) {
15258 // See InputWidget#reusePreInfuseDOM about config.$input
15259 if ( config
.$input
) {
15260 return config
.$input
.addClass( 'oo-ui-element-hidden' );
15262 return $( '<input type="hidden">' );
15266 * Handles menu select events.
15269 * @param {OO.ui.MenuOptionWidget} item Selected menu item
15271 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
15272 this.setValue( item
.getData() );
15278 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
15279 value
= this.cleanUpValue( value
);
15280 this.dropdownWidget
.getMenu().selectItemByData( value
);
15281 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
15288 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
15289 this.dropdownWidget
.setDisabled( state
);
15290 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
15295 * Set the options available for this input.
15297 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15300 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
15302 value
= this.getValue(),
15305 // Rebuild the dropdown menu
15306 this.dropdownWidget
.getMenu()
15308 .addItems( options
.map( function ( opt
) {
15309 var optValue
= widget
.cleanUpValue( opt
.data
);
15310 return new OO
.ui
.MenuOptionWidget( {
15312 label
: opt
.label
!== undefined ? opt
.label
: optValue
15316 // Restore the previous value, or reset to something sensible
15317 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
15318 // Previous value is still available, ensure consistency with the dropdown
15319 this.setValue( value
);
15321 // No longer valid, reset
15322 if ( options
.length
) {
15323 this.setValue( options
[ 0 ].data
);
15333 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
15334 this.dropdownWidget
.getMenu().toggle( true );
15341 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
15342 this.dropdownWidget
.getMenu().toggle( false );
15347 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
15348 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
15349 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
15350 * please see the [OOjs UI documentation on MediaWiki][1].
15352 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15355 * // An example of selected, unselected, and disabled radio inputs
15356 * var radio1 = new OO.ui.RadioInputWidget( {
15360 * var radio2 = new OO.ui.RadioInputWidget( {
15363 * var radio3 = new OO.ui.RadioInputWidget( {
15367 * // Create a fieldset layout with fields for each radio button.
15368 * var fieldset = new OO.ui.FieldsetLayout( {
15369 * label: 'Radio inputs'
15371 * fieldset.addItems( [
15372 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
15373 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
15374 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
15376 * $( 'body' ).append( fieldset.$element );
15378 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15381 * @extends OO.ui.InputWidget
15384 * @param {Object} [config] Configuration options
15385 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
15387 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
15388 // Configuration initialization
15389 config
= config
|| {};
15391 // Parent constructor
15392 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
15396 .addClass( 'oo-ui-radioInputWidget' )
15397 // Required for pretty styling in MediaWiki theme
15398 .append( $( '<span>' ) );
15399 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
15404 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
15406 /* Static Methods */
15411 OO
.ui
.RadioInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
15412 var state
= OO
.ui
.RadioInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
15413 state
.checked
= config
.$input
.prop( 'checked' );
15423 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
15424 return $( '<input type="radio" />' );
15430 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
15431 // RadioInputWidget doesn't track its state.
15435 * Set selection state of this radio button.
15437 * @param {boolean} state `true` for selected
15440 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
15441 // RadioInputWidget doesn't track its state.
15442 this.$input
.prop( 'checked', state
);
15447 * Check if this radio button is selected.
15449 * @return {boolean} Radio is selected
15451 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
15452 return this.$input
.prop( 'checked' );
15458 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
15459 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
15460 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
15461 this.setSelected( state
.checked
);
15466 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
15467 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15468 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15469 * more information about input widgets.
15471 * This and OO.ui.DropdownInputWidget support the same configuration options.
15474 * // Example: A RadioSelectInputWidget with three options
15475 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
15477 * { data: 'a', label: 'First' },
15478 * { data: 'b', label: 'Second'},
15479 * { data: 'c', label: 'Third' }
15482 * $( 'body' ).append( radioSelectInput.$element );
15484 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15487 * @extends OO.ui.InputWidget
15490 * @param {Object} [config] Configuration options
15491 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15493 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
15494 // Configuration initialization
15495 config
= config
|| {};
15497 // Properties (must be done before parent constructor which calls #setDisabled)
15498 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
15500 // Parent constructor
15501 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
15504 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
15507 this.setOptions( config
.options
|| [] );
15509 .addClass( 'oo-ui-radioSelectInputWidget' )
15510 .append( this.radioSelectWidget
.$element
);
15515 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
15517 /* Static Properties */
15519 OO
.ui
.RadioSelectInputWidget
.static.supportsSimpleLabel
= false;
15521 /* Static Methods */
15526 OO
.ui
.RadioSelectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
15527 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
15528 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
15538 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
15539 return $( '<input type="hidden">' );
15543 * Handles menu select events.
15546 * @param {OO.ui.RadioOptionWidget} item Selected menu item
15548 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
15549 this.setValue( item
.getData() );
15555 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
15556 value
= this.cleanUpValue( value
);
15557 this.radioSelectWidget
.selectItemByData( value
);
15558 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
15565 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
15566 this.radioSelectWidget
.setDisabled( state
);
15567 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
15572 * Set the options available for this input.
15574 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15577 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
15579 value
= this.getValue(),
15582 // Rebuild the radioSelect menu
15583 this.radioSelectWidget
15585 .addItems( options
.map( function ( opt
) {
15586 var optValue
= widget
.cleanUpValue( opt
.data
);
15587 return new OO
.ui
.RadioOptionWidget( {
15589 label
: opt
.label
!== undefined ? opt
.label
: optValue
15593 // Restore the previous value, or reset to something sensible
15594 if ( this.radioSelectWidget
.getItemFromData( value
) ) {
15595 // Previous value is still available, ensure consistency with the radioSelect
15596 this.setValue( value
);
15598 // No longer valid, reset
15599 if ( options
.length
) {
15600 this.setValue( options
[ 0 ].data
);
15608 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
15609 * size of the field as well as its presentation. In addition, these widgets can be configured
15610 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
15611 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
15612 * which modifies incoming values rather than validating them.
15613 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
15615 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15618 * // Example of a text input widget
15619 * var textInput = new OO.ui.TextInputWidget( {
15620 * value: 'Text input'
15622 * $( 'body' ).append( textInput.$element );
15624 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15627 * @extends OO.ui.InputWidget
15628 * @mixins OO.ui.mixin.IconElement
15629 * @mixins OO.ui.mixin.IndicatorElement
15630 * @mixins OO.ui.mixin.PendingElement
15631 * @mixins OO.ui.mixin.LabelElement
15634 * @param {Object} [config] Configuration options
15635 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
15636 * 'email' or 'url'. Ignored if `multiline` is true.
15638 * Some values of `type` result in additional behaviors:
15640 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
15641 * empties the text field
15642 * @cfg {string} [placeholder] Placeholder text
15643 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
15644 * instruct the browser to focus this widget.
15645 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
15646 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
15647 * @cfg {boolean} [multiline=false] Allow multiple lines of text
15648 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
15649 * specifies minimum number of rows to display.
15650 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
15651 * Use the #maxRows config to specify a maximum number of displayed rows.
15652 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
15653 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
15654 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
15655 * the value or placeholder text: `'before'` or `'after'`
15656 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
15657 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
15658 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
15659 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
15660 * (the value must contain only numbers); when RegExp, a regular expression that must match the
15661 * value for it to be considered valid; when Function, a function receiving the value as parameter
15662 * that must return true, or promise resolving to true, for it to be considered valid.
15664 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
15665 // Configuration initialization
15666 config
= $.extend( {
15668 labelPosition
: 'after'
15670 if ( config
.type
=== 'search' ) {
15671 if ( config
.icon
=== undefined ) {
15672 config
.icon
= 'search';
15674 // indicator: 'clear' is set dynamically later, depending on value
15676 if ( config
.required
) {
15677 if ( config
.indicator
=== undefined ) {
15678 config
.indicator
= 'required';
15682 // Parent constructor
15683 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
15685 // Mixin constructors
15686 OO
.ui
.mixin
.IconElement
.call( this, config
);
15687 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
15688 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
15689 OO
.ui
.mixin
.LabelElement
.call( this, config
);
15692 this.type
= this.getSaneType( config
);
15693 this.readOnly
= false;
15694 this.multiline
= !!config
.multiline
;
15695 this.autosize
= !!config
.autosize
;
15696 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
15697 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
15698 this.validate
= null;
15699 this.styleHeight
= null;
15700 this.scrollWidth
= null;
15702 // Clone for resizing
15703 if ( this.autosize
) {
15704 this.$clone
= this.$input
15706 .insertAfter( this.$input
)
15707 .attr( 'aria-hidden', 'true' )
15708 .addClass( 'oo-ui-element-hidden' );
15711 this.setValidation( config
.validate
);
15712 this.setLabelPosition( config
.labelPosition
);
15716 keypress
: this.onKeyPress
.bind( this ),
15717 blur
: this.onBlur
.bind( this )
15720 focus
: this.onElementAttach
.bind( this )
15722 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
15723 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
15724 this.on( 'labelChange', this.updatePosition
.bind( this ) );
15725 this.connect( this, {
15726 change
: 'onChange',
15727 disable
: 'onDisable'
15732 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
15733 .append( this.$icon
, this.$indicator
);
15734 this.setReadOnly( !!config
.readOnly
);
15735 this.updateSearchIndicator();
15736 if ( config
.placeholder
) {
15737 this.$input
.attr( 'placeholder', config
.placeholder
);
15739 if ( config
.maxLength
!== undefined ) {
15740 this.$input
.attr( 'maxlength', config
.maxLength
);
15742 if ( config
.autofocus
) {
15743 this.$input
.attr( 'autofocus', 'autofocus' );
15745 if ( config
.required
) {
15746 this.$input
.attr( 'required', 'required' );
15747 this.$input
.attr( 'aria-required', 'true' );
15749 if ( config
.autocomplete
=== false ) {
15750 this.$input
.attr( 'autocomplete', 'off' );
15751 // Turning off autocompletion also disables "form caching" when the user navigates to a
15752 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
15754 beforeunload: function () {
15755 this.$input
.removeAttr( 'autocomplete' );
15757 pageshow: function () {
15758 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
15759 // whole page... it shouldn't hurt, though.
15760 this.$input
.attr( 'autocomplete', 'off' );
15764 if ( this.multiline
&& config
.rows
) {
15765 this.$input
.attr( 'rows', config
.rows
);
15767 if ( this.label
|| config
.autosize
) {
15768 this.installParentChangeDetector();
15774 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
15775 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
15776 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
15777 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
15778 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
15780 /* Static Properties */
15782 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
15787 /* Static Methods */
15792 OO
.ui
.TextInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
15793 var state
= OO
.ui
.TextInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
15794 if ( config
.multiline
) {
15795 state
.scrollTop
= config
.$input
.scrollTop();
15803 * An `enter` event is emitted when the user presses 'enter' inside the text box.
15805 * Not emitted if the input is multiline.
15811 * A `resize` event is emitted when autosize is set and the widget resizes
15819 * Handle icon mouse down events.
15822 * @param {jQuery.Event} e Mouse down event
15825 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
15826 if ( e
.which
=== 1 ) {
15827 this.$input
[ 0 ].focus();
15833 * Handle indicator mouse down events.
15836 * @param {jQuery.Event} e Mouse down event
15839 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
15840 if ( e
.which
=== 1 ) {
15841 if ( this.type
=== 'search' ) {
15842 // Clear the text field
15843 this.setValue( '' );
15845 this.$input
[ 0 ].focus();
15851 * Handle key press events.
15854 * @param {jQuery.Event} e Key press event
15855 * @fires enter If enter key is pressed and input is not multiline
15857 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
15858 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
15859 this.emit( 'enter', e
);
15864 * Handle blur events.
15867 * @param {jQuery.Event} e Blur event
15869 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
15870 this.setValidityFlag();
15874 * Handle element attach events.
15877 * @param {jQuery.Event} e Element attach event
15879 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
15880 // Any previously calculated size is now probably invalid if we reattached elsewhere
15881 this.valCache
= null;
15883 this.positionLabel();
15887 * Handle change events.
15889 * @param {string} value
15892 OO
.ui
.TextInputWidget
.prototype.onChange = function () {
15893 this.updateSearchIndicator();
15894 this.setValidityFlag();
15899 * Handle disable events.
15901 * @param {boolean} disabled Element is disabled
15904 OO
.ui
.TextInputWidget
.prototype.onDisable = function () {
15905 this.updateSearchIndicator();
15909 * Check if the input is {@link #readOnly read-only}.
15911 * @return {boolean}
15913 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
15914 return this.readOnly
;
15918 * Set the {@link #readOnly read-only} state of the input.
15920 * @param {boolean} state Make input read-only
15923 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
15924 this.readOnly
= !!state
;
15925 this.$input
.prop( 'readOnly', this.readOnly
);
15926 this.updateSearchIndicator();
15931 * Support function for making #onElementAttach work across browsers.
15933 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
15934 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
15936 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
15937 * first time that the element gets attached to the documented.
15939 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
15940 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
15941 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
15944 if ( MutationObserver
) {
15945 // The new way. If only it wasn't so ugly.
15947 if ( this.$element
.closest( 'html' ).length
) {
15948 // Widget is attached already, do nothing. This breaks the functionality of this function when
15949 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
15950 // would require observation of the whole document, which would hurt performance of other,
15951 // more important code.
15955 // Find topmost node in the tree
15956 topmostNode
= this.$element
[ 0 ];
15957 while ( topmostNode
.parentNode
) {
15958 topmostNode
= topmostNode
.parentNode
;
15961 // We have no way to detect the $element being attached somewhere without observing the entire
15962 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
15963 // parent node of $element, and instead detect when $element is removed from it (and thus
15964 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
15965 // doesn't get attached, we end up back here and create the parent.
15967 mutationObserver
= new MutationObserver( function ( mutations
) {
15968 var i
, j
, removedNodes
;
15969 for ( i
= 0; i
< mutations
.length
; i
++ ) {
15970 removedNodes
= mutations
[ i
].removedNodes
;
15971 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
15972 if ( removedNodes
[ j
] === topmostNode
) {
15973 setTimeout( onRemove
, 0 );
15980 onRemove = function () {
15981 // If the node was attached somewhere else, report it
15982 if ( widget
.$element
.closest( 'html' ).length
) {
15983 widget
.onElementAttach();
15985 mutationObserver
.disconnect();
15986 widget
.installParentChangeDetector();
15989 // Create a fake parent and observe it
15990 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
15991 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
15993 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
15994 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
15995 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
16000 * Automatically adjust the size of the text input.
16002 * This only affects #multiline inputs that are {@link #autosize autosized}.
16007 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
16008 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
,
16009 idealHeight
, newHeight
, scrollWidth
, property
;
16011 if ( this.multiline
&& this.$input
.val() !== this.valCache
) {
16012 if ( this.autosize
) {
16014 .val( this.$input
.val() )
16015 .attr( 'rows', this.minRows
)
16016 // Set inline height property to 0 to measure scroll height
16017 .css( 'height', 0 );
16019 this.$clone
.removeClass( 'oo-ui-element-hidden' );
16021 this.valCache
= this.$input
.val();
16023 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
16025 // Remove inline height property to measure natural heights
16026 this.$clone
.css( 'height', '' );
16027 innerHeight
= this.$clone
.innerHeight();
16028 outerHeight
= this.$clone
.outerHeight();
16030 // Measure max rows height
16032 .attr( 'rows', this.maxRows
)
16033 .css( 'height', 'auto' )
16035 maxInnerHeight
= this.$clone
.innerHeight();
16037 // Difference between reported innerHeight and scrollHeight with no scrollbars present
16038 // Equals 1 on Blink-based browsers and 0 everywhere else
16039 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
16040 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
16042 this.$clone
.addClass( 'oo-ui-element-hidden' );
16044 // Only apply inline height when expansion beyond natural height is needed
16045 // Use the difference between the inner and outer height as a buffer
16046 newHeight
= idealHeight
> innerHeight
? idealHeight
+ ( outerHeight
- innerHeight
) : '';
16047 if ( newHeight
!== this.styleHeight
) {
16048 this.$input
.css( 'height', newHeight
);
16049 this.styleHeight
= newHeight
;
16050 this.emit( 'resize' );
16053 scrollWidth
= this.$input
[ 0 ].offsetWidth
- this.$input
[ 0 ].clientWidth
;
16054 if ( scrollWidth
!== this.scrollWidth
) {
16055 property
= this.$element
.css( 'direction' ) === 'rtl' ? 'left' : 'right';
16057 this.$label
.css( { right
: '', left
: '' } );
16058 this.$indicator
.css( { right
: '', left
: '' } );
16060 if ( scrollWidth
) {
16061 this.$indicator
.css( property
, scrollWidth
);
16062 if ( this.labelPosition
=== 'after' ) {
16063 this.$label
.css( property
, scrollWidth
);
16067 this.scrollWidth
= scrollWidth
;
16068 this.positionLabel();
16078 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
16079 return config
.multiline
?
16080 $( '<textarea>' ) :
16081 $( '<input type="' + this.getSaneType( config
) + '" />' );
16085 * Get sanitized value for 'type' for given config.
16087 * @param {Object} config Configuration options
16088 * @return {string|null}
16091 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
16092 var type
= [ 'text', 'password', 'search', 'email', 'url' ].indexOf( config
.type
) !== -1 ?
16095 return config
.multiline
? 'multiline' : type
;
16099 * Check if the input supports multiple lines.
16101 * @return {boolean}
16103 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
16104 return !!this.multiline
;
16108 * Check if the input automatically adjusts its size.
16110 * @return {boolean}
16112 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
16113 return !!this.autosize
;
16117 * Focus the input and select a specified range within the text.
16119 * @param {number} from Select from offset
16120 * @param {number} [to] Select to offset, defaults to from
16123 OO
.ui
.TextInputWidget
.prototype.selectRange = function ( from, to
) {
16124 var textRange
, isBackwards
, start
, end
,
16125 element
= this.$input
[ 0 ];
16129 isBackwards
= to
< from;
16130 start
= isBackwards
? to
: from;
16131 end
= isBackwards
? from : to
;
16135 if ( element
.setSelectionRange
) {
16136 element
.setSelectionRange( start
, end
, isBackwards
? 'backward' : 'forward' );
16137 } else if ( element
.createTextRange
) {
16139 textRange
= element
.createTextRange();
16140 textRange
.collapse( true );
16141 textRange
.moveStart( 'character', start
);
16142 textRange
.moveEnd( 'character', end
- start
);
16143 textRange
.select();
16149 * Get the length of the text input value.
16151 * This could differ from the length of #getValue if the
16152 * value gets filtered
16154 * @return {number} Input length
16156 OO
.ui
.TextInputWidget
.prototype.getInputLength = function () {
16157 return this.$input
[ 0 ].value
.length
;
16161 * Focus the input and select the entire text.
16165 OO
.ui
.TextInputWidget
.prototype.select = function () {
16166 return this.selectRange( 0, this.getInputLength() );
16170 * Focus the input and move the cursor to the start.
16174 OO
.ui
.TextInputWidget
.prototype.moveCursorToStart = function () {
16175 return this.selectRange( 0 );
16179 * Focus the input and move the cursor to the end.
16183 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
16184 return this.selectRange( this.getInputLength() );
16188 * Set the validation pattern.
16190 * The validation pattern is either a regular expression, a function, or the symbolic name of a
16191 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
16192 * value must contain only numbers).
16194 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
16195 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
16197 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
16198 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
16199 this.validate
= validate
;
16201 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
16206 * Sets the 'invalid' flag appropriately.
16208 * @param {boolean} [isValid] Optionally override validation result
16210 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
16212 setFlag = function ( valid
) {
16214 widget
.$input
.attr( 'aria-invalid', 'true' );
16216 widget
.$input
.removeAttr( 'aria-invalid' );
16218 widget
.setFlags( { invalid
: !valid
} );
16221 if ( isValid
!== undefined ) {
16222 setFlag( isValid
);
16224 this.getValidity().then( function () {
16233 * Check if a value is valid.
16235 * This method returns a promise that resolves with a boolean `true` if the current value is
16236 * considered valid according to the supplied {@link #validate validation pattern}.
16239 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
16241 OO
.ui
.TextInputWidget
.prototype.isValid = function () {
16244 if ( this.validate
instanceof Function
) {
16245 result
= this.validate( this.getValue() );
16246 if ( $.isFunction( result
.promise
) ) {
16247 return result
.promise();
16249 return $.Deferred().resolve( !!result
).promise();
16252 return $.Deferred().resolve( !!this.getValue().match( this.validate
) ).promise();
16257 * Get the validity of current value.
16259 * This method returns a promise that resolves if the value is valid and rejects if
16260 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
16262 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
16264 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
16265 var result
, promise
;
16267 function rejectOrResolve( valid
) {
16269 return $.Deferred().resolve().promise();
16271 return $.Deferred().reject().promise();
16275 if ( this.validate
instanceof Function
) {
16276 result
= this.validate( this.getValue() );
16278 if ( $.isFunction( result
.promise
) ) {
16279 promise
= $.Deferred();
16281 result
.then( function ( valid
) {
16291 return promise
.promise();
16293 return rejectOrResolve( result
);
16296 return rejectOrResolve( this.getValue().match( this.validate
) );
16301 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
16303 * @param {string} labelPosition Label position, 'before' or 'after'
16306 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
16307 this.labelPosition
= labelPosition
;
16308 this.updatePosition();
16313 * Deprecated alias of #setLabelPosition
16315 * @deprecated Use setLabelPosition instead.
16317 OO
.ui
.TextInputWidget
.prototype.setPosition
=
16318 OO
.ui
.TextInputWidget
.prototype.setLabelPosition
;
16321 * Update the position of the inline label.
16323 * This method is called by #setLabelPosition, and can also be called on its own if
16324 * something causes the label to be mispositioned.
16328 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
16329 var after
= this.labelPosition
=== 'after';
16332 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
16333 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
16335 this.valCache
= null;
16336 this.scrollWidth
= null;
16338 this.positionLabel();
16344 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
16345 * already empty or when it's not editable.
16347 OO
.ui
.TextInputWidget
.prototype.updateSearchIndicator = function () {
16348 if ( this.type
=== 'search' ) {
16349 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
16350 this.setIndicator( null );
16352 this.setIndicator( 'clear' );
16358 * Position the label by setting the correct padding on the input.
16363 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
16364 var after
, rtl
, property
;
16365 // Clear old values
16367 // Clear old values if present
16369 'padding-right': '',
16373 if ( this.label
) {
16374 this.$element
.append( this.$label
);
16376 this.$label
.detach();
16380 after
= this.labelPosition
=== 'after';
16381 rtl
= this.$element
.css( 'direction' ) === 'rtl';
16382 property
= after
=== rtl
? 'padding-left' : 'padding-right';
16384 this.$input
.css( property
, this.$label
.outerWidth( true ) + ( after
? this.scrollWidth
: 0 ) );
16392 OO
.ui
.TextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
16393 OO
.ui
.TextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
16394 if ( state
.scrollTop
!== undefined ) {
16395 this.$input
.scrollTop( state
.scrollTop
);
16400 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
16401 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
16402 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
16404 * - by typing a value in the text input field. If the value exactly matches the value of a menu
16405 * option, that option will appear to be selected.
16406 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
16409 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
16412 * // Example: A ComboBoxWidget.
16413 * var comboBox = new OO.ui.ComboBoxWidget( {
16414 * label: 'ComboBoxWidget',
16415 * input: { value: 'Option One' },
16418 * new OO.ui.MenuOptionWidget( {
16419 * data: 'Option 1',
16420 * label: 'Option One'
16422 * new OO.ui.MenuOptionWidget( {
16423 * data: 'Option 2',
16424 * label: 'Option Two'
16426 * new OO.ui.MenuOptionWidget( {
16427 * data: 'Option 3',
16428 * label: 'Option Three'
16430 * new OO.ui.MenuOptionWidget( {
16431 * data: 'Option 4',
16432 * label: 'Option Four'
16434 * new OO.ui.MenuOptionWidget( {
16435 * data: 'Option 5',
16436 * label: 'Option Five'
16441 * $( 'body' ).append( comboBox.$element );
16443 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16446 * @extends OO.ui.Widget
16447 * @mixins OO.ui.mixin.TabIndexedElement
16450 * @param {Object} [config] Configuration options
16451 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
16452 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
16453 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
16454 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
16455 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
16457 OO
.ui
.ComboBoxWidget
= function OoUiComboBoxWidget( config
) {
16458 // Configuration initialization
16459 config
= config
|| {};
16461 // Parent constructor
16462 OO
.ui
.ComboBoxWidget
.parent
.call( this, config
);
16464 // Properties (must be set before TabIndexedElement constructor call)
16465 this.$indicator
= this.$( '<span>' );
16467 // Mixin constructors
16468 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$indicator
} ) );
16471 this.$overlay
= config
.$overlay
|| this.$element
;
16472 this.input
= new OO
.ui
.TextInputWidget( $.extend(
16475 $indicator
: this.$indicator
,
16476 disabled
: this.isDisabled()
16480 this.input
.$input
.eq( 0 ).attr( {
16482 'aria-autocomplete': 'list'
16484 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
16488 $container
: this.input
.$element
,
16489 disabled
: this.isDisabled()
16495 this.$indicator
.on( {
16496 click
: this.onClick
.bind( this ),
16497 keypress
: this.onKeyPress
.bind( this )
16499 this.input
.connect( this, {
16500 change
: 'onInputChange',
16501 enter
: 'onInputEnter'
16503 this.menu
.connect( this, {
16504 choose
: 'onMenuChoose',
16505 add
: 'onMenuItemsChange',
16506 remove
: 'onMenuItemsChange'
16510 this.$element
.addClass( 'oo-ui-comboBoxWidget' ).append( this.input
.$element
);
16511 this.$overlay
.append( this.menu
.$element
);
16512 this.onMenuItemsChange();
16517 OO
.inheritClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.Widget
);
16518 OO
.mixinClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.mixin
.TabIndexedElement
);
16523 * Get the combobox's menu.
16524 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
16526 OO
.ui
.ComboBoxWidget
.prototype.getMenu = function () {
16531 * Get the combobox's text input widget.
16532 * @return {OO.ui.TextInputWidget} Text input widget
16534 OO
.ui
.ComboBoxWidget
.prototype.getInput = function () {
16539 * Handle input change events.
16542 * @param {string} value New value
16544 OO
.ui
.ComboBoxWidget
.prototype.onInputChange = function ( value
) {
16545 var match
= this.menu
.getItemFromData( value
);
16547 this.menu
.selectItem( match
);
16548 if ( this.menu
.getHighlightedItem() ) {
16549 this.menu
.highlightItem( match
);
16552 if ( !this.isDisabled() ) {
16553 this.menu
.toggle( true );
16558 * Handle mouse click events.
16561 * @param {jQuery.Event} e Mouse click event
16563 OO
.ui
.ComboBoxWidget
.prototype.onClick = function ( e
) {
16564 if ( !this.isDisabled() && e
.which
=== 1 ) {
16565 this.menu
.toggle();
16566 this.input
.$input
[ 0 ].focus();
16572 * Handle key press events.
16575 * @param {jQuery.Event} e Key press event
16577 OO
.ui
.ComboBoxWidget
.prototype.onKeyPress = function ( e
) {
16578 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
16579 this.menu
.toggle();
16580 this.input
.$input
[ 0 ].focus();
16586 * Handle input enter events.
16590 OO
.ui
.ComboBoxWidget
.prototype.onInputEnter = function () {
16591 if ( !this.isDisabled() ) {
16592 this.menu
.toggle( false );
16597 * Handle menu choose events.
16600 * @param {OO.ui.OptionWidget} item Chosen item
16602 OO
.ui
.ComboBoxWidget
.prototype.onMenuChoose = function ( item
) {
16603 this.input
.setValue( item
.getData() );
16607 * Handle menu item change events.
16611 OO
.ui
.ComboBoxWidget
.prototype.onMenuItemsChange = function () {
16612 var match
= this.menu
.getItemFromData( this.input
.getValue() );
16613 this.menu
.selectItem( match
);
16614 if ( this.menu
.getHighlightedItem() ) {
16615 this.menu
.highlightItem( match
);
16617 this.$element
.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu
.isEmpty() );
16623 OO
.ui
.ComboBoxWidget
.prototype.setDisabled = function ( disabled
) {
16625 OO
.ui
.ComboBoxWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
16627 if ( this.input
) {
16628 this.input
.setDisabled( this.isDisabled() );
16631 this.menu
.setDisabled( this.isDisabled() );
16638 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
16639 * be configured with a `label` option that is set to a string, a label node, or a function:
16641 * - String: a plaintext string
16642 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
16643 * label that includes a link or special styling, such as a gray color or additional graphical elements.
16644 * - Function: a function that will produce a string in the future. Functions are used
16645 * in cases where the value of the label is not currently defined.
16647 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
16648 * will come into focus when the label is clicked.
16651 * // Examples of LabelWidgets
16652 * var label1 = new OO.ui.LabelWidget( {
16653 * label: 'plaintext label'
16655 * var label2 = new OO.ui.LabelWidget( {
16656 * label: $( '<a href="default.html">jQuery label</a>' )
16658 * // Create a fieldset layout with fields for each example
16659 * var fieldset = new OO.ui.FieldsetLayout();
16660 * fieldset.addItems( [
16661 * new OO.ui.FieldLayout( label1 ),
16662 * new OO.ui.FieldLayout( label2 )
16664 * $( 'body' ).append( fieldset.$element );
16667 * @extends OO.ui.Widget
16668 * @mixins OO.ui.mixin.LabelElement
16671 * @param {Object} [config] Configuration options
16672 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
16673 * Clicking the label will focus the specified input field.
16675 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
16676 // Configuration initialization
16677 config
= config
|| {};
16679 // Parent constructor
16680 OO
.ui
.LabelWidget
.parent
.call( this, config
);
16682 // Mixin constructors
16683 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
16684 OO
.ui
.mixin
.TitledElement
.call( this, config
);
16687 this.input
= config
.input
;
16690 if ( this.input
instanceof OO
.ui
.InputWidget
) {
16691 this.$element
.on( 'click', this.onClick
.bind( this ) );
16695 this.$element
.addClass( 'oo-ui-labelWidget' );
16700 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
16701 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
16702 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
16704 /* Static Properties */
16706 OO
.ui
.LabelWidget
.static.tagName
= 'span';
16711 * Handles label mouse click events.
16714 * @param {jQuery.Event} e Mouse click event
16716 OO
.ui
.LabelWidget
.prototype.onClick = function () {
16717 this.input
.simulateLabelClick();
16722 * OptionWidgets are special elements that can be selected and configured with data. The
16723 * data is often unique for each option, but it does not have to be. OptionWidgets are used
16724 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
16725 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
16727 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16730 * @extends OO.ui.Widget
16731 * @mixins OO.ui.mixin.LabelElement
16732 * @mixins OO.ui.mixin.FlaggedElement
16735 * @param {Object} [config] Configuration options
16737 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
16738 // Configuration initialization
16739 config
= config
|| {};
16741 // Parent constructor
16742 OO
.ui
.OptionWidget
.parent
.call( this, config
);
16744 // Mixin constructors
16745 OO
.ui
.mixin
.ItemWidget
.call( this );
16746 OO
.ui
.mixin
.LabelElement
.call( this, config
);
16747 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
16750 this.selected
= false;
16751 this.highlighted
= false;
16752 this.pressed
= false;
16756 .data( 'oo-ui-optionWidget', this )
16757 .attr( 'role', 'option' )
16758 .attr( 'aria-selected', 'false' )
16759 .addClass( 'oo-ui-optionWidget' )
16760 .append( this.$label
);
16765 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
16766 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
16767 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
16768 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
16770 /* Static Properties */
16772 OO
.ui
.OptionWidget
.static.selectable
= true;
16774 OO
.ui
.OptionWidget
.static.highlightable
= true;
16776 OO
.ui
.OptionWidget
.static.pressable
= true;
16778 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
16783 * Check if the option can be selected.
16785 * @return {boolean} Item is selectable
16787 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
16788 return this.constructor.static.selectable
&& !this.isDisabled() && this.isVisible();
16792 * Check if the option can be highlighted. A highlight indicates that the option
16793 * may be selected when a user presses enter or clicks. Disabled items cannot
16796 * @return {boolean} Item is highlightable
16798 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
16799 return this.constructor.static.highlightable
&& !this.isDisabled() && this.isVisible();
16803 * Check if the option can be pressed. The pressed state occurs when a user mouses
16804 * down on an item, but has not yet let go of the mouse.
16806 * @return {boolean} Item is pressable
16808 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
16809 return this.constructor.static.pressable
&& !this.isDisabled() && this.isVisible();
16813 * Check if the option is selected.
16815 * @return {boolean} Item is selected
16817 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
16818 return this.selected
;
16822 * Check if the option is highlighted. A highlight indicates that the
16823 * item may be selected when a user presses enter or clicks.
16825 * @return {boolean} Item is highlighted
16827 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
16828 return this.highlighted
;
16832 * Check if the option is pressed. The pressed state occurs when a user mouses
16833 * down on an item, but has not yet let go of the mouse. The item may appear
16834 * selected, but it will not be selected until the user releases the mouse.
16836 * @return {boolean} Item is pressed
16838 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
16839 return this.pressed
;
16843 * Set the option’s selected state. In general, all modifications to the selection
16844 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
16845 * method instead of this method.
16847 * @param {boolean} [state=false] Select option
16850 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
16851 if ( this.constructor.static.selectable
) {
16852 this.selected
= !!state
;
16854 .toggleClass( 'oo-ui-optionWidget-selected', state
)
16855 .attr( 'aria-selected', state
.toString() );
16856 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
16857 this.scrollElementIntoView();
16859 this.updateThemeClasses();
16865 * Set the option’s highlighted state. In general, all programmatic
16866 * modifications to the highlight should be handled by the
16867 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
16868 * method instead of this method.
16870 * @param {boolean} [state=false] Highlight option
16873 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
16874 if ( this.constructor.static.highlightable
) {
16875 this.highlighted
= !!state
;
16876 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
16877 this.updateThemeClasses();
16883 * Set the option’s pressed state. In general, all
16884 * programmatic modifications to the pressed state should be handled by the
16885 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
16886 * method instead of this method.
16888 * @param {boolean} [state=false] Press option
16891 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
16892 if ( this.constructor.static.pressable
) {
16893 this.pressed
= !!state
;
16894 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
16895 this.updateThemeClasses();
16901 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
16902 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
16903 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
16904 * options. For more information about options and selects, please see the
16905 * [OOjs UI documentation on MediaWiki][1].
16908 * // Decorated options in a select widget
16909 * var select = new OO.ui.SelectWidget( {
16911 * new OO.ui.DecoratedOptionWidget( {
16913 * label: 'Option with icon',
16916 * new OO.ui.DecoratedOptionWidget( {
16918 * label: 'Option with indicator',
16919 * indicator: 'next'
16923 * $( 'body' ).append( select.$element );
16925 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16928 * @extends OO.ui.OptionWidget
16929 * @mixins OO.ui.mixin.IconElement
16930 * @mixins OO.ui.mixin.IndicatorElement
16933 * @param {Object} [config] Configuration options
16935 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
16936 // Parent constructor
16937 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
16939 // Mixin constructors
16940 OO
.ui
.mixin
.IconElement
.call( this, config
);
16941 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
16945 .addClass( 'oo-ui-decoratedOptionWidget' )
16946 .prepend( this.$icon
)
16947 .append( this.$indicator
);
16952 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
16953 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
16954 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
16957 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
16958 * can be selected and configured with data. The class is
16959 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
16960 * [OOjs UI documentation on MediaWiki] [1] for more information.
16962 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
16965 * @extends OO.ui.DecoratedOptionWidget
16966 * @mixins OO.ui.mixin.ButtonElement
16967 * @mixins OO.ui.mixin.TabIndexedElement
16968 * @mixins OO.ui.mixin.TitledElement
16971 * @param {Object} [config] Configuration options
16973 OO
.ui
.ButtonOptionWidget
= function OoUiButtonOptionWidget( config
) {
16974 // Configuration initialization
16975 config
= config
|| {};
16977 // Parent constructor
16978 OO
.ui
.ButtonOptionWidget
.parent
.call( this, config
);
16980 // Mixin constructors
16981 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
16982 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
16983 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, {
16984 $tabIndexed
: this.$button
,
16989 this.$element
.addClass( 'oo-ui-buttonOptionWidget' );
16990 this.$button
.append( this.$element
.contents() );
16991 this.$element
.append( this.$button
);
16996 OO
.inheritClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
16997 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.ButtonElement
);
16998 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.TitledElement
);
16999 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.TabIndexedElement
);
17001 /* Static Properties */
17003 // Allow button mouse down events to pass through so they can be handled by the parent select widget
17004 OO
.ui
.ButtonOptionWidget
.static.cancelButtonMouseDownEvents
= false;
17006 OO
.ui
.ButtonOptionWidget
.static.highlightable
= false;
17013 OO
.ui
.ButtonOptionWidget
.prototype.setSelected = function ( state
) {
17014 OO
.ui
.ButtonOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
17016 if ( this.constructor.static.selectable
) {
17017 this.setActive( state
);
17024 * RadioOptionWidget is an option widget that looks like a radio button.
17025 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
17026 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
17028 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
17031 * @extends OO.ui.OptionWidget
17034 * @param {Object} [config] Configuration options
17036 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
17037 // Configuration initialization
17038 config
= config
|| {};
17040 // Properties (must be done before parent constructor which calls #setDisabled)
17041 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
17043 // Parent constructor
17044 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
17047 this.radio
.$input
.on( 'focus', this.onInputFocus
.bind( this ) );
17050 // Remove implicit role, we're handling it ourselves
17051 this.radio
.$input
.attr( 'role', 'presentation' );
17053 .addClass( 'oo-ui-radioOptionWidget' )
17054 .attr( 'role', 'radio' )
17055 .attr( 'aria-checked', 'false' )
17056 .removeAttr( 'aria-selected' )
17057 .prepend( this.radio
.$element
);
17062 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
17064 /* Static Properties */
17066 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
17068 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
17070 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
17072 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
17077 * @param {jQuery.Event} e Focus event
17080 OO
.ui
.RadioOptionWidget
.prototype.onInputFocus = function () {
17081 this.radio
.$input
.blur();
17082 this.$element
.parent().focus();
17088 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
17089 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
17091 this.radio
.setSelected( state
);
17093 .attr( 'aria-checked', state
.toString() )
17094 .removeAttr( 'aria-selected' );
17102 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
17103 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
17105 this.radio
.setDisabled( this.isDisabled() );
17111 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
17112 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
17113 * the [OOjs UI documentation on MediaWiki] [1] for more information.
17115 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
17118 * @extends OO.ui.DecoratedOptionWidget
17121 * @param {Object} [config] Configuration options
17123 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
17124 // Configuration initialization
17125 config
= $.extend( { icon
: 'check' }, config
);
17127 // Parent constructor
17128 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
17132 .attr( 'role', 'menuitem' )
17133 .addClass( 'oo-ui-menuOptionWidget' );
17138 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
17140 /* Static Properties */
17142 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
17145 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
17146 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
17149 * var myDropdown = new OO.ui.DropdownWidget( {
17152 * new OO.ui.MenuSectionOptionWidget( {
17155 * new OO.ui.MenuOptionWidget( {
17157 * label: 'Welsh Corgi'
17159 * new OO.ui.MenuOptionWidget( {
17161 * label: 'Standard Poodle'
17163 * new OO.ui.MenuSectionOptionWidget( {
17166 * new OO.ui.MenuOptionWidget( {
17173 * $( 'body' ).append( myDropdown.$element );
17176 * @extends OO.ui.DecoratedOptionWidget
17179 * @param {Object} [config] Configuration options
17181 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
17182 // Parent constructor
17183 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
17186 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' );
17191 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
17193 /* Static Properties */
17195 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
17197 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
17200 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
17202 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
17203 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
17207 * @extends OO.ui.DecoratedOptionWidget
17210 * @param {Object} [config] Configuration options
17211 * @cfg {number} [level] Indentation level
17212 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
17214 OO
.ui
.OutlineOptionWidget
= function OoUiOutlineOptionWidget( config
) {
17215 // Configuration initialization
17216 config
= config
|| {};
17218 // Parent constructor
17219 OO
.ui
.OutlineOptionWidget
.parent
.call( this, config
);
17223 this.movable
= !!config
.movable
;
17224 this.removable
= !!config
.removable
;
17227 this.$element
.addClass( 'oo-ui-outlineOptionWidget' );
17228 this.setLevel( config
.level
);
17233 OO
.inheritClass( OO
.ui
.OutlineOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
17235 /* Static Properties */
17237 OO
.ui
.OutlineOptionWidget
.static.highlightable
= false;
17239 OO
.ui
.OutlineOptionWidget
.static.scrollIntoViewOnSelect
= true;
17241 OO
.ui
.OutlineOptionWidget
.static.levelClass
= 'oo-ui-outlineOptionWidget-level-';
17243 OO
.ui
.OutlineOptionWidget
.static.levels
= 3;
17248 * Check if item is movable.
17250 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17252 * @return {boolean} Item is movable
17254 OO
.ui
.OutlineOptionWidget
.prototype.isMovable = function () {
17255 return this.movable
;
17259 * Check if item is removable.
17261 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17263 * @return {boolean} Item is removable
17265 OO
.ui
.OutlineOptionWidget
.prototype.isRemovable = function () {
17266 return this.removable
;
17270 * Get indentation level.
17272 * @return {number} Indentation level
17274 OO
.ui
.OutlineOptionWidget
.prototype.getLevel = function () {
17281 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17283 * @param {boolean} movable Item is movable
17286 OO
.ui
.OutlineOptionWidget
.prototype.setMovable = function ( movable
) {
17287 this.movable
= !!movable
;
17288 this.updateThemeClasses();
17293 * Set removability.
17295 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17297 * @param {boolean} movable Item is removable
17300 OO
.ui
.OutlineOptionWidget
.prototype.setRemovable = function ( removable
) {
17301 this.removable
= !!removable
;
17302 this.updateThemeClasses();
17307 * Set indentation level.
17309 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
17312 OO
.ui
.OutlineOptionWidget
.prototype.setLevel = function ( level
) {
17313 var levels
= this.constructor.static.levels
,
17314 levelClass
= this.constructor.static.levelClass
,
17317 this.level
= level
? Math
.max( 0, Math
.min( levels
- 1, level
) ) : 0;
17319 if ( this.level
=== i
) {
17320 this.$element
.addClass( levelClass
+ i
);
17322 this.$element
.removeClass( levelClass
+ i
);
17325 this.updateThemeClasses();
17331 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
17333 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
17334 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
17338 * @extends OO.ui.OptionWidget
17341 * @param {Object} [config] Configuration options
17343 OO
.ui
.TabOptionWidget
= function OoUiTabOptionWidget( config
) {
17344 // Configuration initialization
17345 config
= config
|| {};
17347 // Parent constructor
17348 OO
.ui
.TabOptionWidget
.parent
.call( this, config
);
17351 this.$element
.addClass( 'oo-ui-tabOptionWidget' );
17356 OO
.inheritClass( OO
.ui
.TabOptionWidget
, OO
.ui
.OptionWidget
);
17358 /* Static Properties */
17360 OO
.ui
.TabOptionWidget
.static.highlightable
= false;
17363 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
17364 * By default, each popup has an anchor that points toward its origin.
17365 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
17368 * // A popup widget.
17369 * var popup = new OO.ui.PopupWidget( {
17370 * $content: $( '<p>Hi there!</p>' ),
17375 * $( 'body' ).append( popup.$element );
17376 * // To display the popup, toggle the visibility to 'true'.
17377 * popup.toggle( true );
17379 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
17382 * @extends OO.ui.Widget
17383 * @mixins OO.ui.mixin.LabelElement
17384 * @mixins OO.ui.mixin.ClippableElement
17387 * @param {Object} [config] Configuration options
17388 * @cfg {number} [width=320] Width of popup in pixels
17389 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
17390 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
17391 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
17392 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
17393 * popup is leaning towards the right of the screen.
17394 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
17395 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
17396 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
17397 * sentence in the given language.
17398 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
17399 * See the [OOjs UI docs on MediaWiki][3] for an example.
17400 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
17401 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
17402 * @cfg {jQuery} [$content] Content to append to the popup's body
17403 * @cfg {jQuery} [$footer] Content to append to the popup's footer
17404 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
17405 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
17406 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
17408 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
17409 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
17411 * @cfg {boolean} [padded] Add padding to the popup's body
17413 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
17414 // Configuration initialization
17415 config
= config
|| {};
17417 // Parent constructor
17418 OO
.ui
.PopupWidget
.parent
.call( this, config
);
17420 // Properties (must be set before ClippableElement constructor call)
17421 this.$body
= $( '<div>' );
17422 this.$popup
= $( '<div>' );
17424 // Mixin constructors
17425 OO
.ui
.mixin
.LabelElement
.call( this, config
);
17426 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, {
17427 $clippable
: this.$body
,
17428 $clippableContainer
: this.$popup
17432 this.$head
= $( '<div>' );
17433 this.$footer
= $( '<div>' );
17434 this.$anchor
= $( '<div>' );
17435 // If undefined, will be computed lazily in updateDimensions()
17436 this.$container
= config
.$container
;
17437 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
17438 this.autoClose
= !!config
.autoClose
;
17439 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
17440 this.transitionTimeout
= null;
17441 this.anchor
= null;
17442 this.width
= config
.width
!== undefined ? config
.width
: 320;
17443 this.height
= config
.height
!== undefined ? config
.height
: null;
17444 this.setAlignment( config
.align
);
17445 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
17446 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
17447 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
17450 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
17453 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
17454 this.$body
.addClass( 'oo-ui-popupWidget-body' );
17455 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
17457 .addClass( 'oo-ui-popupWidget-head' )
17458 .append( this.$label
, this.closeButton
.$element
);
17459 this.$footer
.addClass( 'oo-ui-popupWidget-footer' );
17460 if ( !config
.head
) {
17461 this.$head
.addClass( 'oo-ui-element-hidden' );
17463 if ( !config
.$footer
) {
17464 this.$footer
.addClass( 'oo-ui-element-hidden' );
17467 .addClass( 'oo-ui-popupWidget-popup' )
17468 .append( this.$head
, this.$body
, this.$footer
);
17470 .addClass( 'oo-ui-popupWidget' )
17471 .append( this.$popup
, this.$anchor
);
17472 // Move content, which was added to #$element by OO.ui.Widget, to the body
17473 if ( config
.$content
instanceof jQuery
) {
17474 this.$body
.append( config
.$content
);
17476 if ( config
.$footer
instanceof jQuery
) {
17477 this.$footer
.append( config
.$footer
);
17479 if ( config
.padded
) {
17480 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
17483 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
17484 // that reference properties not initialized at that time of parent class construction
17485 // TODO: Find a better way to handle post-constructor setup
17486 this.visible
= false;
17487 this.$element
.addClass( 'oo-ui-element-hidden' );
17492 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
17493 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
17494 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
17499 * Handles mouse down events.
17502 * @param {MouseEvent} e Mouse down event
17504 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
17506 this.isVisible() &&
17507 !$.contains( this.$element
[ 0 ], e
.target
) &&
17508 ( !this.$autoCloseIgnore
|| !this.$autoCloseIgnore
.has( e
.target
).length
)
17510 this.toggle( false );
17515 * Bind mouse down listener.
17519 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
17520 // Capture clicks outside popup
17521 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler
);
17525 * Handles close button click events.
17529 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
17530 if ( this.isVisible() ) {
17531 this.toggle( false );
17536 * Unbind mouse down listener.
17540 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
17541 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler
);
17545 * Handles key down events.
17548 * @param {KeyboardEvent} e Key down event
17550 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
17552 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
17555 this.toggle( false );
17556 e
.preventDefault();
17557 e
.stopPropagation();
17562 * Bind key down listener.
17566 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
17567 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler
);
17571 * Unbind key down listener.
17575 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
17576 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler
);
17580 * Show, hide, or toggle the visibility of the anchor.
17582 * @param {boolean} [show] Show anchor, omit to toggle
17584 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
17585 show
= show
=== undefined ? !this.anchored
: !!show
;
17587 if ( this.anchored
!== show
) {
17589 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
17591 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
17593 this.anchored
= show
;
17598 * Check if the anchor is visible.
17600 * @return {boolean} Anchor is visible
17602 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
17603 return this.anchor
;
17609 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
17611 show
= show
=== undefined ? !this.isVisible() : !!show
;
17613 change
= show
!== this.isVisible();
17616 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
17620 if ( this.autoClose
) {
17621 this.bindMouseDownListener();
17622 this.bindKeyDownListener();
17624 this.updateDimensions();
17625 this.toggleClipping( true );
17627 this.toggleClipping( false );
17628 if ( this.autoClose
) {
17629 this.unbindMouseDownListener();
17630 this.unbindKeyDownListener();
17639 * Set the size of the popup.
17641 * Changing the size may also change the popup's position depending on the alignment.
17643 * @param {number} width Width in pixels
17644 * @param {number} height Height in pixels
17645 * @param {boolean} [transition=false] Use a smooth transition
17648 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
17649 this.width
= width
;
17650 this.height
= height
!== undefined ? height
: null;
17651 if ( this.isVisible() ) {
17652 this.updateDimensions( transition
);
17657 * Update the size and position.
17659 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
17660 * be called automatically.
17662 * @param {boolean} [transition=false] Use a smooth transition
17665 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
17666 var popupOffset
, originOffset
, containerLeft
, containerWidth
, containerRight
,
17667 popupLeft
, popupRight
, overlapLeft
, overlapRight
, anchorWidth
,
17668 align
= this.align
,
17671 if ( !this.$container
) {
17672 // Lazy-initialize $container if not specified in constructor
17673 this.$container
= $( this.getClosestScrollableElementContainer() );
17676 // Set height and width before measuring things, since it might cause our measurements
17677 // to change (e.g. due to scrollbars appearing or disappearing)
17680 height
: this.height
!== null ? this.height
: 'auto'
17683 // If we are in RTL, we need to flip the alignment, unless it is center
17684 if ( align
=== 'forwards' || align
=== 'backwards' ) {
17685 if ( this.$container
.css( 'direction' ) === 'rtl' ) {
17686 align
= ( { forwards
: 'force-left', backwards
: 'force-right' } )[ this.align
];
17688 align
= ( { forwards
: 'force-right', backwards
: 'force-left' } )[ this.align
];
17693 // Compute initial popupOffset based on alignment
17694 popupOffset
= this.width
* ( { 'force-left': -1, center
: -0.5, 'force-right': 0 } )[ align
];
17696 // Figure out if this will cause the popup to go beyond the edge of the container
17697 originOffset
= this.$element
.offset().left
;
17698 containerLeft
= this.$container
.offset().left
;
17699 containerWidth
= this.$container
.innerWidth();
17700 containerRight
= containerLeft
+ containerWidth
;
17701 popupLeft
= popupOffset
- this.containerPadding
;
17702 popupRight
= popupOffset
+ this.containerPadding
+ this.width
+ this.containerPadding
;
17703 overlapLeft
= ( originOffset
+ popupLeft
) - containerLeft
;
17704 overlapRight
= containerRight
- ( originOffset
+ popupRight
);
17706 // Adjust offset to make the popup not go beyond the edge, if needed
17707 if ( overlapRight
< 0 ) {
17708 popupOffset
+= overlapRight
;
17709 } else if ( overlapLeft
< 0 ) {
17710 popupOffset
-= overlapLeft
;
17713 // Adjust offset to avoid anchor being rendered too close to the edge
17714 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
17715 // TODO: Find a measurement that works for CSS anchors and image anchors
17716 anchorWidth
= this.$anchor
[ 0 ].scrollWidth
* 2;
17717 if ( popupOffset
+ this.width
< anchorWidth
) {
17718 popupOffset
= anchorWidth
- this.width
;
17719 } else if ( -popupOffset
< anchorWidth
) {
17720 popupOffset
= -anchorWidth
;
17723 // Prevent transition from being interrupted
17724 clearTimeout( this.transitionTimeout
);
17725 if ( transition
) {
17726 // Enable transition
17727 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
17730 // Position body relative to anchor
17731 this.$popup
.css( 'margin-left', popupOffset
);
17733 if ( transition
) {
17734 // Prevent transitioning after transition is complete
17735 this.transitionTimeout
= setTimeout( function () {
17736 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
17739 // Prevent transitioning immediately
17740 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
17743 // Reevaluate clipping state since we've relocated and resized the popup
17750 * Set popup alignment
17751 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17752 * `backwards` or `forwards`.
17754 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
17755 // Validate alignment and transform deprecated values
17756 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
17757 this.align
= { left
: 'force-right', right
: 'force-left' }[ align
] || align
;
17759 this.align
= 'center';
17764 * Get popup alignment
17765 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17766 * `backwards` or `forwards`.
17768 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
17773 * Progress bars visually display the status of an operation, such as a download,
17774 * and can be either determinate or indeterminate:
17776 * - **determinate** process bars show the percent of an operation that is complete.
17778 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
17779 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
17780 * not use percentages.
17782 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
17785 * // Examples of determinate and indeterminate progress bars.
17786 * var progressBar1 = new OO.ui.ProgressBarWidget( {
17789 * var progressBar2 = new OO.ui.ProgressBarWidget();
17791 * // Create a FieldsetLayout to layout progress bars
17792 * var fieldset = new OO.ui.FieldsetLayout;
17793 * fieldset.addItems( [
17794 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
17795 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
17797 * $( 'body' ).append( fieldset.$element );
17800 * @extends OO.ui.Widget
17803 * @param {Object} [config] Configuration options
17804 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
17805 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
17806 * By default, the progress bar is indeterminate.
17808 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
17809 // Configuration initialization
17810 config
= config
|| {};
17812 // Parent constructor
17813 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
17816 this.$bar
= $( '<div>' );
17817 this.progress
= null;
17820 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
17821 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
17824 role
: 'progressbar',
17825 'aria-valuemin': 0,
17826 'aria-valuemax': 100
17828 .addClass( 'oo-ui-progressBarWidget' )
17829 .append( this.$bar
);
17834 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
17836 /* Static Properties */
17838 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
17843 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
17845 * @return {number|boolean} Progress percent
17847 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
17848 return this.progress
;
17852 * Set the percent of the process completed or `false` for an indeterminate process.
17854 * @param {number|boolean} progress Progress percent or `false` for indeterminate
17856 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
17857 this.progress
= progress
;
17859 if ( progress
!== false ) {
17860 this.$bar
.css( 'width', this.progress
+ '%' );
17861 this.$element
.attr( 'aria-valuenow', this.progress
);
17863 this.$bar
.css( 'width', '' );
17864 this.$element
.removeAttr( 'aria-valuenow' );
17866 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress
);
17870 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
17871 * and a menu of search results, which is displayed beneath the query
17872 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
17873 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
17874 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
17876 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
17877 * the [OOjs UI demos][1] for an example.
17879 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
17882 * @extends OO.ui.Widget
17885 * @param {Object} [config] Configuration options
17886 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
17887 * @cfg {string} [value] Initial query value
17889 OO
.ui
.SearchWidget
= function OoUiSearchWidget( config
) {
17890 // Configuration initialization
17891 config
= config
|| {};
17893 // Parent constructor
17894 OO
.ui
.SearchWidget
.parent
.call( this, config
);
17897 this.query
= new OO
.ui
.TextInputWidget( {
17899 placeholder
: config
.placeholder
,
17900 value
: config
.value
17902 this.results
= new OO
.ui
.SelectWidget();
17903 this.$query
= $( '<div>' );
17904 this.$results
= $( '<div>' );
17907 this.query
.connect( this, {
17908 change
: 'onQueryChange',
17909 enter
: 'onQueryEnter'
17911 this.query
.$input
.on( 'keydown', this.onQueryKeydown
.bind( this ) );
17915 .addClass( 'oo-ui-searchWidget-query' )
17916 .append( this.query
.$element
);
17918 .addClass( 'oo-ui-searchWidget-results' )
17919 .append( this.results
.$element
);
17921 .addClass( 'oo-ui-searchWidget' )
17922 .append( this.$results
, this.$query
);
17927 OO
.inheritClass( OO
.ui
.SearchWidget
, OO
.ui
.Widget
);
17932 * Handle query key down events.
17935 * @param {jQuery.Event} e Key down event
17937 OO
.ui
.SearchWidget
.prototype.onQueryKeydown = function ( e
) {
17938 var highlightedItem
, nextItem
,
17939 dir
= e
.which
=== OO
.ui
.Keys
.DOWN
? 1 : ( e
.which
=== OO
.ui
.Keys
.UP
? -1 : 0 );
17942 highlightedItem
= this.results
.getHighlightedItem();
17943 if ( !highlightedItem
) {
17944 highlightedItem
= this.results
.getSelectedItem();
17946 nextItem
= this.results
.getRelativeSelectableItem( highlightedItem
, dir
);
17947 this.results
.highlightItem( nextItem
);
17948 nextItem
.scrollElementIntoView();
17953 * Handle select widget select events.
17955 * Clears existing results. Subclasses should repopulate items according to new query.
17958 * @param {string} value New value
17960 OO
.ui
.SearchWidget
.prototype.onQueryChange = function () {
17962 this.results
.clearItems();
17966 * Handle select widget enter key events.
17968 * Chooses highlighted item.
17971 * @param {string} value New value
17973 OO
.ui
.SearchWidget
.prototype.onQueryEnter = function () {
17974 var highlightedItem
= this.results
.getHighlightedItem();
17975 if ( highlightedItem
) {
17976 this.results
.chooseItem( highlightedItem
);
17981 * Get the query input.
17983 * @return {OO.ui.TextInputWidget} Query input
17985 OO
.ui
.SearchWidget
.prototype.getQuery = function () {
17990 * Get the search results menu.
17992 * @return {OO.ui.SelectWidget} Menu of search results
17994 OO
.ui
.SearchWidget
.prototype.getResults = function () {
17995 return this.results
;
17999 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
18000 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
18001 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
18004 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
18005 * information, please see the [OOjs UI documentation on MediaWiki][1].
18008 * // Example of a select widget with three options
18009 * var select = new OO.ui.SelectWidget( {
18011 * new OO.ui.OptionWidget( {
18013 * label: 'Option One',
18015 * new OO.ui.OptionWidget( {
18017 * label: 'Option Two',
18019 * new OO.ui.OptionWidget( {
18021 * label: 'Option Three',
18025 * $( 'body' ).append( select.$element );
18027 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18031 * @extends OO.ui.Widget
18032 * @mixins OO.ui.mixin.GroupWidget
18035 * @param {Object} [config] Configuration options
18036 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
18037 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
18038 * the [OOjs UI documentation on MediaWiki] [2] for examples.
18039 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18041 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
18042 // Configuration initialization
18043 config
= config
|| {};
18045 // Parent constructor
18046 OO
.ui
.SelectWidget
.parent
.call( this, config
);
18048 // Mixin constructors
18049 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
18052 this.pressed
= false;
18053 this.selecting
= null;
18054 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
18055 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
18056 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
18057 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
18058 this.keyPressBuffer
= '';
18059 this.keyPressBufferTimer
= null;
18062 this.connect( this, {
18065 this.$element
.on( {
18066 mousedown
: this.onMouseDown
.bind( this ),
18067 mouseover
: this.onMouseOver
.bind( this ),
18068 mouseleave
: this.onMouseLeave
.bind( this )
18073 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
18074 .attr( 'role', 'listbox' );
18075 if ( Array
.isArray( config
.items
) ) {
18076 this.addItems( config
.items
);
18082 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
18084 // Need to mixin base class as well
18085 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupElement
);
18086 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
18089 OO
.ui
.SelectWidget
.static.passAllFilter = function () {
18098 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
18100 * @param {OO.ui.OptionWidget|null} item Highlighted item
18106 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
18107 * pressed state of an option.
18109 * @param {OO.ui.OptionWidget|null} item Pressed item
18115 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
18117 * @param {OO.ui.OptionWidget|null} item Selected item
18122 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
18123 * @param {OO.ui.OptionWidget} item Chosen item
18129 * An `add` event is emitted when options are added to the select with the #addItems method.
18131 * @param {OO.ui.OptionWidget[]} items Added items
18132 * @param {number} index Index of insertion point
18138 * A `remove` event is emitted when options are removed from the select with the #clearItems
18139 * or #removeItems methods.
18141 * @param {OO.ui.OptionWidget[]} items Removed items
18147 * Handle mouse down events.
18150 * @param {jQuery.Event} e Mouse down event
18152 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
18155 if ( !this.isDisabled() && e
.which
=== 1 ) {
18156 this.togglePressed( true );
18157 item
= this.getTargetItem( e
);
18158 if ( item
&& item
.isSelectable() ) {
18159 this.pressItem( item
);
18160 this.selecting
= item
;
18161 OO
.ui
.addCaptureEventListener(
18162 this.getElementDocument(),
18164 this.onMouseUpHandler
18166 OO
.ui
.addCaptureEventListener(
18167 this.getElementDocument(),
18169 this.onMouseMoveHandler
18177 * Handle mouse up events.
18180 * @param {jQuery.Event} e Mouse up event
18182 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
18185 this.togglePressed( false );
18186 if ( !this.selecting
) {
18187 item
= this.getTargetItem( e
);
18188 if ( item
&& item
.isSelectable() ) {
18189 this.selecting
= item
;
18192 if ( !this.isDisabled() && e
.which
=== 1 && this.selecting
) {
18193 this.pressItem( null );
18194 this.chooseItem( this.selecting
);
18195 this.selecting
= null;
18198 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup',
18199 this.onMouseUpHandler
);
18200 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mousemove',
18201 this.onMouseMoveHandler
);
18207 * Handle mouse move events.
18210 * @param {jQuery.Event} e Mouse move event
18212 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
18215 if ( !this.isDisabled() && this.pressed
) {
18216 item
= this.getTargetItem( e
);
18217 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
18218 this.pressItem( item
);
18219 this.selecting
= item
;
18226 * Handle mouse over events.
18229 * @param {jQuery.Event} e Mouse over event
18231 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
18234 if ( !this.isDisabled() ) {
18235 item
= this.getTargetItem( e
);
18236 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
18242 * Handle mouse leave events.
18245 * @param {jQuery.Event} e Mouse over event
18247 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
18248 if ( !this.isDisabled() ) {
18249 this.highlightItem( null );
18255 * Handle key down events.
18258 * @param {jQuery.Event} e Key down event
18260 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
18263 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
18265 if ( !this.isDisabled() && this.isVisible() ) {
18266 switch ( e
.keyCode
) {
18267 case OO
.ui
.Keys
.ENTER
:
18268 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
18269 // Was only highlighted, now let's select it. No-op if already selected.
18270 this.chooseItem( currentItem
);
18274 case OO
.ui
.Keys
.UP
:
18275 case OO
.ui
.Keys
.LEFT
:
18276 this.clearKeyPressBuffer();
18277 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
18280 case OO
.ui
.Keys
.DOWN
:
18281 case OO
.ui
.Keys
.RIGHT
:
18282 this.clearKeyPressBuffer();
18283 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
18286 case OO
.ui
.Keys
.ESCAPE
:
18287 case OO
.ui
.Keys
.TAB
:
18288 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
18289 currentItem
.setHighlighted( false );
18291 this.unbindKeyDownListener();
18292 this.unbindKeyPressListener();
18293 // Don't prevent tabbing away / defocusing
18299 if ( nextItem
.constructor.static.highlightable
) {
18300 this.highlightItem( nextItem
);
18302 this.chooseItem( nextItem
);
18304 nextItem
.scrollElementIntoView();
18308 // Can't just return false, because e is not always a jQuery event
18309 e
.preventDefault();
18310 e
.stopPropagation();
18316 * Bind key down listener.
18320 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
18321 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler
);
18325 * Unbind key down listener.
18329 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
18330 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler
);
18334 * Clear the key-press buffer
18338 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
18339 if ( this.keyPressBufferTimer
) {
18340 clearTimeout( this.keyPressBufferTimer
);
18341 this.keyPressBufferTimer
= null;
18343 this.keyPressBuffer
= '';
18347 * Handle key press events.
18350 * @param {jQuery.Event} e Key press event
18352 OO
.ui
.SelectWidget
.prototype.onKeyPress = function ( e
) {
18353 var c
, filter
, item
;
18355 if ( !e
.charCode
) {
18356 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
18357 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
18362 if ( String
.fromCodePoint
) {
18363 c
= String
.fromCodePoint( e
.charCode
);
18365 c
= String
.fromCharCode( e
.charCode
);
18368 if ( this.keyPressBufferTimer
) {
18369 clearTimeout( this.keyPressBufferTimer
);
18371 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
18373 item
= this.getHighlightedItem() || this.getSelectedItem();
18375 if ( this.keyPressBuffer
=== c
) {
18376 // Common (if weird) special case: typing "xxxx" will cycle through all
18377 // the items beginning with "x".
18379 item
= this.getRelativeSelectableItem( item
, 1 );
18382 this.keyPressBuffer
+= c
;
18385 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
18386 if ( !item
|| !filter( item
) ) {
18387 item
= this.getRelativeSelectableItem( item
, 1, filter
);
18390 if ( item
.constructor.static.highlightable
) {
18391 this.highlightItem( item
);
18393 this.chooseItem( item
);
18395 item
.scrollElementIntoView();
18402 * Get a matcher for the specific string
18405 * @param {string} s String to match against items
18406 * @param {boolean} [exact=false] Only accept exact matches
18407 * @return {Function} function ( OO.ui.OptionItem ) => boolean
18409 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
, exact
) {
18412 if ( s
.normalize
) {
18415 s
= exact
? s
.trim() : s
.replace( /^\s+/, '' );
18416 re
= '^\\s*' + s
.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
18420 re
= new RegExp( re
, 'i' );
18421 return function ( item
) {
18422 var l
= item
.getLabel();
18423 if ( typeof l
!== 'string' ) {
18424 l
= item
.$label
.text();
18426 if ( l
.normalize
) {
18429 return re
.test( l
);
18434 * Bind key press listener.
18438 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
18439 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler
);
18443 * Unbind key down listener.
18445 * If you override this, be sure to call this.clearKeyPressBuffer() from your
18450 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
18451 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler
);
18452 this.clearKeyPressBuffer();
18456 * Visibility change handler
18459 * @param {boolean} visible
18461 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
18463 this.clearKeyPressBuffer();
18468 * Get the closest item to a jQuery.Event.
18471 * @param {jQuery.Event} e
18472 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
18474 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
18475 return $( e
.target
).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
18479 * Get selected item.
18481 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
18483 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
18486 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18487 if ( this.items
[ i
].isSelected() ) {
18488 return this.items
[ i
];
18495 * Get highlighted item.
18497 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
18499 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
18502 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18503 if ( this.items
[ i
].isHighlighted() ) {
18504 return this.items
[ i
];
18511 * Toggle pressed state.
18513 * Press is a state that occurs when a user mouses down on an item, but
18514 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
18515 * until the user releases the mouse.
18517 * @param {boolean} pressed An option is being pressed
18519 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
18520 if ( pressed
=== undefined ) {
18521 pressed
= !this.pressed
;
18523 if ( pressed
!== this.pressed
) {
18525 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
18526 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
18527 this.pressed
= pressed
;
18532 * Highlight an option. If the `item` param is omitted, no options will be highlighted
18533 * and any existing highlight will be removed. The highlight is mutually exclusive.
18535 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
18539 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
18540 var i
, len
, highlighted
,
18543 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18544 highlighted
= this.items
[ i
] === item
;
18545 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
18546 this.items
[ i
].setHighlighted( highlighted
);
18551 this.emit( 'highlight', item
);
18558 * Fetch an item by its label.
18560 * @param {string} label Label of the item to select.
18561 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18562 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
18564 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
18565 var i
, item
, found
,
18566 len
= this.items
.length
,
18567 filter
= this.getItemMatcher( label
, true );
18569 for ( i
= 0; i
< len
; i
++ ) {
18570 item
= this.items
[ i
];
18571 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
18578 filter
= this.getItemMatcher( label
, false );
18579 for ( i
= 0; i
< len
; i
++ ) {
18580 item
= this.items
[ i
];
18581 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
18597 * Programmatically select an option by its label. If the item does not exist,
18598 * all options will be deselected.
18600 * @param {string} [label] Label of the item to select.
18601 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18605 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
18606 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
18607 if ( label
=== undefined || !itemFromLabel
) {
18608 return this.selectItem();
18610 return this.selectItem( itemFromLabel
);
18614 * Programmatically select an option by its data. If the `data` parameter is omitted,
18615 * or if the item does not exist, all options will be deselected.
18617 * @param {Object|string} [data] Value of the item to select, omit to deselect all
18621 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
18622 var itemFromData
= this.getItemFromData( data
);
18623 if ( data
=== undefined || !itemFromData
) {
18624 return this.selectItem();
18626 return this.selectItem( itemFromData
);
18630 * Programmatically select an option by its reference. If the `item` parameter is omitted,
18631 * all options will be deselected.
18633 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
18637 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
18638 var i
, len
, selected
,
18641 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18642 selected
= this.items
[ i
] === item
;
18643 if ( this.items
[ i
].isSelected() !== selected
) {
18644 this.items
[ i
].setSelected( selected
);
18649 this.emit( 'select', item
);
18658 * Press is a state that occurs when a user mouses down on an item, but has not
18659 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
18660 * releases the mouse.
18662 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
18666 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
18667 var i
, len
, pressed
,
18670 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18671 pressed
= this.items
[ i
] === item
;
18672 if ( this.items
[ i
].isPressed() !== pressed
) {
18673 this.items
[ i
].setPressed( pressed
);
18678 this.emit( 'press', item
);
18687 * Note that ‘choose’ should never be modified programmatically. A user can choose
18688 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
18689 * use the #selectItem method.
18691 * This method is identical to #selectItem, but may vary in subclasses that take additional action
18692 * when users choose an item with the keyboard or mouse.
18694 * @param {OO.ui.OptionWidget} item Item to choose
18698 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
18700 this.selectItem( item
);
18701 this.emit( 'choose', item
);
18708 * Get an option by its position relative to the specified item (or to the start of the option array,
18709 * if item is `null`). The direction in which to search through the option array is specified with a
18710 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
18711 * `null` if there are no options in the array.
18713 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
18714 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
18715 * @param {Function} filter Only consider items for which this function returns
18716 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
18717 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
18719 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
, filter
) {
18720 var currentIndex
, nextIndex
, i
,
18721 increase
= direction
> 0 ? 1 : -1,
18722 len
= this.items
.length
;
18724 if ( !$.isFunction( filter
) ) {
18725 filter
= OO
.ui
.SelectWidget
.static.passAllFilter
;
18728 if ( item
instanceof OO
.ui
.OptionWidget
) {
18729 currentIndex
= this.items
.indexOf( item
);
18730 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
18732 // If no item is selected and moving forward, start at the beginning.
18733 // If moving backward, start at the end.
18734 nextIndex
= direction
> 0 ? 0 : len
- 1;
18737 for ( i
= 0; i
< len
; i
++ ) {
18738 item
= this.items
[ nextIndex
];
18739 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
18742 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
18748 * Get the next selectable item or `null` if there are no selectable items.
18749 * Disabled options and menu-section markers and breaks are not selectable.
18751 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
18753 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
18756 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18757 item
= this.items
[ i
];
18758 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() ) {
18767 * Add an array of options to the select. Optionally, an index number can be used to
18768 * specify an insertion point.
18770 * @param {OO.ui.OptionWidget[]} items Items to add
18771 * @param {number} [index] Index to insert items after
18775 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
18777 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
18779 // Always provide an index, even if it was omitted
18780 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
18786 * Remove the specified array of options from the select. Options will be detached
18787 * from the DOM, not removed, so they can be reused later. To remove all options from
18788 * the select, you may wish to use the #clearItems method instead.
18790 * @param {OO.ui.OptionWidget[]} items Items to remove
18794 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
18797 // Deselect items being removed
18798 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
18800 if ( item
.isSelected() ) {
18801 this.selectItem( null );
18806 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
18808 this.emit( 'remove', items
);
18814 * Clear all options from the select. Options will be detached from the DOM, not removed,
18815 * so that they can be reused later. To remove a subset of options from the select, use
18816 * the #removeItems method.
18821 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
18822 var items
= this.items
.slice();
18825 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
18828 this.selectItem( null );
18830 this.emit( 'remove', items
);
18836 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
18837 * button options and is used together with
18838 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
18839 * highlighting, choosing, and selecting mutually exclusive options. Please see
18840 * the [OOjs UI documentation on MediaWiki] [1] for more information.
18843 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
18844 * var option1 = new OO.ui.ButtonOptionWidget( {
18846 * label: 'Option 1',
18847 * title: 'Button option 1'
18850 * var option2 = new OO.ui.ButtonOptionWidget( {
18852 * label: 'Option 2',
18853 * title: 'Button option 2'
18856 * var option3 = new OO.ui.ButtonOptionWidget( {
18858 * label: 'Option 3',
18859 * title: 'Button option 3'
18862 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
18863 * items: [ option1, option2, option3 ]
18865 * $( 'body' ).append( buttonSelect.$element );
18867 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18870 * @extends OO.ui.SelectWidget
18871 * @mixins OO.ui.mixin.TabIndexedElement
18874 * @param {Object} [config] Configuration options
18876 OO
.ui
.ButtonSelectWidget
= function OoUiButtonSelectWidget( config
) {
18877 // Parent constructor
18878 OO
.ui
.ButtonSelectWidget
.parent
.call( this, config
);
18880 // Mixin constructors
18881 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
18884 this.$element
.on( {
18885 focus
: this.bindKeyDownListener
.bind( this ),
18886 blur
: this.unbindKeyDownListener
.bind( this )
18890 this.$element
.addClass( 'oo-ui-buttonSelectWidget' );
18895 OO
.inheritClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.SelectWidget
);
18896 OO
.mixinClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
18899 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
18900 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
18901 * an interface for adding, removing and selecting options.
18902 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18904 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
18905 * OO.ui.RadioSelectInputWidget instead.
18908 * // A RadioSelectWidget with RadioOptions.
18909 * var option1 = new OO.ui.RadioOptionWidget( {
18911 * label: 'Selected radio option'
18914 * var option2 = new OO.ui.RadioOptionWidget( {
18916 * label: 'Unselected radio option'
18919 * var radioSelect=new OO.ui.RadioSelectWidget( {
18920 * items: [ option1, option2 ]
18923 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
18924 * radioSelect.selectItem( option1 );
18926 * $( 'body' ).append( radioSelect.$element );
18928 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18932 * @extends OO.ui.SelectWidget
18933 * @mixins OO.ui.mixin.TabIndexedElement
18936 * @param {Object} [config] Configuration options
18938 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
18939 // Parent constructor
18940 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
18942 // Mixin constructors
18943 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
18946 this.$element
.on( {
18947 focus
: this.bindKeyDownListener
.bind( this ),
18948 blur
: this.unbindKeyDownListener
.bind( this )
18953 .addClass( 'oo-ui-radioSelectWidget' )
18954 .attr( 'role', 'radiogroup' );
18959 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
18960 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
18963 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
18964 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
18965 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
18966 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
18967 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
18968 * and customized to be opened, closed, and displayed as needed.
18970 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
18971 * mouse outside the menu.
18973 * Menus also have support for keyboard interaction:
18975 * - Enter/Return key: choose and select a menu option
18976 * - Up-arrow key: highlight the previous menu option
18977 * - Down-arrow key: highlight the next menu option
18978 * - Esc key: hide the menu
18980 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18981 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18984 * @extends OO.ui.SelectWidget
18985 * @mixins OO.ui.mixin.ClippableElement
18988 * @param {Object} [config] Configuration options
18989 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
18990 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
18991 * and {@link OO.ui.mixin.LookupElement LookupElement}
18992 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
18993 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiSelectWidget CapsuleMultiSelectWidget}
18994 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
18995 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
18996 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
18997 * that button, unless the button (or its parent widget) is passed in here.
18998 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
18999 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
19001 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
19002 // Configuration initialization
19003 config
= config
|| {};
19005 // Parent constructor
19006 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
19008 // Mixin constructors
19009 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
19012 this.newItems
= null;
19013 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
19014 this.filterFromInput
= !!config
.filterFromInput
;
19015 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
19016 this.$widget
= config
.widget
? config
.widget
.$element
: null;
19017 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
19018 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
19022 .addClass( 'oo-ui-menuSelectWidget' )
19023 .attr( 'role', 'menu' );
19025 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
19026 // that reference properties not initialized at that time of parent class construction
19027 // TODO: Find a better way to handle post-constructor setup
19028 this.visible
= false;
19029 this.$element
.addClass( 'oo-ui-element-hidden' );
19034 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
19035 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
19040 * Handles document mouse down events.
19043 * @param {jQuery.Event} e Key down event
19045 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
19047 !OO
.ui
.contains( this.$element
[ 0 ], e
.target
, true ) &&
19048 ( !this.$widget
|| !OO
.ui
.contains( this.$widget
[ 0 ], e
.target
, true ) )
19050 this.toggle( false );
19057 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
19058 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
19060 if ( !this.isDisabled() && this.isVisible() ) {
19061 switch ( e
.keyCode
) {
19062 case OO
.ui
.Keys
.LEFT
:
19063 case OO
.ui
.Keys
.RIGHT
:
19064 // Do nothing if a text field is associated, arrow keys will be handled natively
19065 if ( !this.$input
) {
19066 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
19069 case OO
.ui
.Keys
.ESCAPE
:
19070 case OO
.ui
.Keys
.TAB
:
19071 if ( currentItem
) {
19072 currentItem
.setHighlighted( false );
19074 this.toggle( false );
19075 // Don't prevent tabbing away, prevent defocusing
19076 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
19077 e
.preventDefault();
19078 e
.stopPropagation();
19082 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
19089 * Update menu item visibility after input changes.
19092 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
19094 len
= this.items
.length
,
19095 showAll
= !this.isVisible(),
19096 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() );
19098 for ( i
= 0; i
< len
; i
++ ) {
19099 item
= this.items
[ i
];
19100 if ( item
instanceof OO
.ui
.OptionWidget
) {
19101 item
.toggle( showAll
|| filter( item
) );
19105 // Reevaluate clipping
19112 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
19113 if ( this.$input
) {
19114 this.$input
.on( 'keydown', this.onKeyDownHandler
);
19116 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyDownListener
.call( this );
19123 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
19124 if ( this.$input
) {
19125 this.$input
.off( 'keydown', this.onKeyDownHandler
);
19127 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyDownListener
.call( this );
19134 OO
.ui
.MenuSelectWidget
.prototype.bindKeyPressListener = function () {
19135 if ( this.$input
) {
19136 if ( this.filterFromInput
) {
19137 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
19140 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyPressListener
.call( this );
19147 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyPressListener = function () {
19148 if ( this.$input
) {
19149 if ( this.filterFromInput
) {
19150 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
19151 this.updateItemVisibility();
19154 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyPressListener
.call( this );
19161 * When a user chooses an item, the menu is closed.
19163 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
19164 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
19165 * @param {OO.ui.OptionWidget} item Item to choose
19168 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
19169 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
19170 this.toggle( false );
19177 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
19181 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
19184 if ( !this.newItems
) {
19185 this.newItems
= [];
19188 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
19190 if ( this.isVisible() ) {
19191 // Defer fitting label until item has been attached
19194 this.newItems
.push( item
);
19198 // Reevaluate clipping
19207 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
19209 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
19211 // Reevaluate clipping
19220 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
19222 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
19224 // Reevaluate clipping
19233 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
19234 var i
, len
, change
;
19236 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
19237 change
= visible
!== this.isVisible();
19240 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
19244 this.bindKeyDownListener();
19245 this.bindKeyPressListener();
19247 if ( this.newItems
&& this.newItems
.length
) {
19248 for ( i
= 0, len
= this.newItems
.length
; i
< len
; i
++ ) {
19249 this.newItems
[ i
].fitLabel();
19251 this.newItems
= null;
19253 this.toggleClipping( true );
19256 if ( this.autoHide
) {
19257 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler
);
19260 this.unbindKeyDownListener();
19261 this.unbindKeyPressListener();
19262 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler
);
19263 this.toggleClipping( false );
19271 * FloatingMenuSelectWidget is a menu that will stick under a specified
19272 * container, even when it is inserted elsewhere in the document (for example,
19273 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
19274 * menu from being clipped too aggresively.
19276 * The menu's position is automatically calculated and maintained when the menu
19277 * is toggled or the window is resized.
19279 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
19282 * @extends OO.ui.MenuSelectWidget
19283 * @mixins OO.ui.mixin.FloatableElement
19286 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
19287 * Deprecated, omit this parameter and specify `$container` instead.
19288 * @param {Object} [config] Configuration options
19289 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
19291 OO
.ui
.FloatingMenuSelectWidget
= function OoUiFloatingMenuSelectWidget( inputWidget
, config
) {
19292 // Allow 'inputWidget' parameter and config for backwards compatibility
19293 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
19294 config
= inputWidget
;
19295 inputWidget
= config
.inputWidget
;
19298 // Configuration initialization
19299 config
= config
|| {};
19301 // Parent constructor
19302 OO
.ui
.FloatingMenuSelectWidget
.parent
.call( this, config
);
19304 // Properties (must be set before mixin constructors)
19305 this.inputWidget
= inputWidget
; // For backwards compatibility
19306 this.$container
= config
.$container
|| this.inputWidget
.$element
;
19308 // Mixins constructors
19309 OO
.ui
.mixin
.FloatableElement
.call( this, $.extend( {}, config
, { $floatableContainer
: this.$container
} ) );
19312 this.$element
.addClass( 'oo-ui-floatingMenuSelectWidget' );
19313 // For backwards compatibility
19314 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
19319 OO
.inheritClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
19320 OO
.mixinClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.mixin
.FloatableElement
);
19322 // For backwards compatibility
19323 OO
.ui
.TextInputMenuSelectWidget
= OO
.ui
.FloatingMenuSelectWidget
;
19330 OO
.ui
.FloatingMenuSelectWidget
.prototype.toggle = function ( visible
) {
19332 visible
= visible
=== undefined ? !this.isVisible() : !!visible
;
19333 change
= visible
!== this.isVisible();
19335 if ( change
&& visible
) {
19336 // Make sure the width is set before the parent method runs.
19337 this.setIdealSize( this.$container
.width() );
19341 // This will call this.clip(), which is nonsensical since we're not positioned yet...
19342 OO
.ui
.FloatingMenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
19345 this.togglePositioning( this.isVisible() );
19352 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
19353 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
19355 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
19358 * @extends OO.ui.SelectWidget
19359 * @mixins OO.ui.mixin.TabIndexedElement
19362 * @param {Object} [config] Configuration options
19364 OO
.ui
.OutlineSelectWidget
= function OoUiOutlineSelectWidget( config
) {
19365 // Parent constructor
19366 OO
.ui
.OutlineSelectWidget
.parent
.call( this, config
);
19368 // Mixin constructors
19369 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
19372 this.$element
.on( {
19373 focus
: this.bindKeyDownListener
.bind( this ),
19374 blur
: this.unbindKeyDownListener
.bind( this )
19378 this.$element
.addClass( 'oo-ui-outlineSelectWidget' );
19383 OO
.inheritClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.SelectWidget
);
19384 OO
.mixinClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
19387 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
19389 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
19392 * @extends OO.ui.SelectWidget
19393 * @mixins OO.ui.mixin.TabIndexedElement
19396 * @param {Object} [config] Configuration options
19398 OO
.ui
.TabSelectWidget
= function OoUiTabSelectWidget( config
) {
19399 // Parent constructor
19400 OO
.ui
.TabSelectWidget
.parent
.call( this, config
);
19402 // Mixin constructors
19403 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
19406 this.$element
.on( {
19407 focus
: this.bindKeyDownListener
.bind( this ),
19408 blur
: this.unbindKeyDownListener
.bind( this )
19412 this.$element
.addClass( 'oo-ui-tabSelectWidget' );
19417 OO
.inheritClass( OO
.ui
.TabSelectWidget
, OO
.ui
.SelectWidget
);
19418 OO
.mixinClass( OO
.ui
.TabSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
19421 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
19422 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
19423 * (to adjust the value in increments) to allow the user to enter a number.
19426 * // Example: A NumberInputWidget.
19427 * var numberInput = new OO.ui.NumberInputWidget( {
19428 * label: 'NumberInputWidget',
19429 * input: { value: 5, min: 1, max: 10 }
19431 * $( 'body' ).append( numberInput.$element );
19434 * @extends OO.ui.Widget
19437 * @param {Object} [config] Configuration options
19438 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
19439 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
19440 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
19441 * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
19442 * @cfg {number} [min=-Infinity] Minimum allowed value
19443 * @cfg {number} [max=Infinity] Maximum allowed value
19444 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
19445 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
19447 OO
.ui
.NumberInputWidget
= function OoUiNumberInputWidget( config
) {
19448 // Configuration initialization
19449 config
= $.extend( {
19457 // Parent constructor
19458 OO
.ui
.NumberInputWidget
.parent
.call( this, config
);
19461 this.input
= new OO
.ui
.TextInputWidget( $.extend(
19463 disabled
: this.isDisabled()
19467 this.minusButton
= new OO
.ui
.ButtonWidget( $.extend(
19469 disabled
: this.isDisabled(),
19472 config
.minusButton
,
19474 classes
: [ 'oo-ui-numberInputWidget-minusButton' ],
19478 this.plusButton
= new OO
.ui
.ButtonWidget( $.extend(
19480 disabled
: this.isDisabled(),
19485 classes
: [ 'oo-ui-numberInputWidget-plusButton' ],
19491 this.input
.connect( this, {
19492 change
: this.emit
.bind( this, 'change' ),
19493 enter
: this.emit
.bind( this, 'enter' )
19495 this.input
.$input
.on( {
19496 keydown
: this.onKeyDown
.bind( this ),
19497 'wheel mousewheel DOMMouseScroll': this.onWheel
.bind( this )
19499 this.plusButton
.connect( this, {
19500 click
: [ 'onButtonClick', +1 ]
19502 this.minusButton
.connect( this, {
19503 click
: [ 'onButtonClick', -1 ]
19507 this.setIsInteger( !!config
.isInteger
);
19508 this.setRange( config
.min
, config
.max
);
19509 this.setStep( config
.step
, config
.pageStep
);
19511 this.$field
= $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
19513 this.minusButton
.$element
,
19514 this.input
.$element
,
19515 this.plusButton
.$element
19517 this.$element
.addClass( 'oo-ui-numberInputWidget' ).append( this.$field
);
19518 this.input
.setValidation( this.validateNumber
.bind( this ) );
19523 OO
.inheritClass( OO
.ui
.NumberInputWidget
, OO
.ui
.Widget
);
19528 * A `change` event is emitted when the value of the input changes.
19534 * An `enter` event is emitted when the user presses 'enter' inside the text box.
19542 * Set whether only integers are allowed
19543 * @param {boolean} flag
19545 OO
.ui
.NumberInputWidget
.prototype.setIsInteger = function ( flag
) {
19546 this.isInteger
= !!flag
;
19547 this.input
.setValidityFlag();
19551 * Get whether only integers are allowed
19552 * @return {boolean} Flag value
19554 OO
.ui
.NumberInputWidget
.prototype.getIsInteger = function () {
19555 return this.isInteger
;
19559 * Set the range of allowed values
19560 * @param {number} min Minimum allowed value
19561 * @param {number} max Maximum allowed value
19563 OO
.ui
.NumberInputWidget
.prototype.setRange = function ( min
, max
) {
19565 throw new Error( 'Minimum (' + min
+ ') must not be greater than maximum (' + max
+ ')' );
19569 this.input
.setValidityFlag();
19573 * Get the current range
19574 * @return {number[]} Minimum and maximum values
19576 OO
.ui
.NumberInputWidget
.prototype.getRange = function () {
19577 return [ this.min
, this.max
];
19581 * Set the stepping deltas
19582 * @param {number} step Normal step
19583 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
19585 OO
.ui
.NumberInputWidget
.prototype.setStep = function ( step
, pageStep
) {
19587 throw new Error( 'Step value must be positive' );
19589 if ( pageStep
=== null ) {
19590 pageStep
= step
* 10;
19591 } else if ( pageStep
<= 0 ) {
19592 throw new Error( 'Page step value must be positive' );
19595 this.pageStep
= pageStep
;
19599 * Get the current stepping values
19600 * @return {number[]} Step and page step
19602 OO
.ui
.NumberInputWidget
.prototype.getStep = function () {
19603 return [ this.step
, this.pageStep
];
19607 * Get the current value of the widget
19610 OO
.ui
.NumberInputWidget
.prototype.getValue = function () {
19611 return this.input
.getValue();
19615 * Get the current value of the widget as a number
19616 * @return {number} May be NaN, or an invalid number
19618 OO
.ui
.NumberInputWidget
.prototype.getNumericValue = function () {
19619 return +this.input
.getValue();
19623 * Set the value of the widget
19624 * @param {string} value Invalid values are allowed
19626 OO
.ui
.NumberInputWidget
.prototype.setValue = function ( value
) {
19627 this.input
.setValue( value
);
19631 * Adjust the value of the widget
19632 * @param {number} delta Adjustment amount
19634 OO
.ui
.NumberInputWidget
.prototype.adjustValue = function ( delta
) {
19635 var n
, v
= this.getNumericValue();
19638 if ( isNaN( delta
) || !isFinite( delta
) ) {
19639 throw new Error( 'Delta must be a finite number' );
19642 if ( isNaN( v
) ) {
19646 n
= Math
.max( Math
.min( n
, this.max
), this.min
);
19647 if ( this.isInteger
) {
19648 n
= Math
.round( n
);
19653 this.setValue( n
);
19660 * @param {string} value Field value
19661 * @return {boolean}
19663 OO
.ui
.NumberInputWidget
.prototype.validateNumber = function ( value
) {
19665 if ( isNaN( n
) || !isFinite( n
) ) {
19669 /*jshint bitwise: false */
19670 if ( this.isInteger
&& ( n
| 0 ) !== n
) {
19673 /*jshint bitwise: true */
19675 if ( n
< this.min
|| n
> this.max
) {
19683 * Handle mouse click events.
19686 * @param {number} dir +1 or -1
19688 OO
.ui
.NumberInputWidget
.prototype.onButtonClick = function ( dir
) {
19689 this.adjustValue( dir
* this.step
);
19693 * Handle mouse wheel events.
19696 * @param {jQuery.Event} event
19698 OO
.ui
.NumberInputWidget
.prototype.onWheel = function ( event
) {
19701 // Standard 'wheel' event
19702 if ( event
.originalEvent
.deltaMode
!== undefined ) {
19703 this.sawWheelEvent
= true;
19705 if ( event
.originalEvent
.deltaY
) {
19706 delta
= -event
.originalEvent
.deltaY
;
19707 } else if ( event
.originalEvent
.deltaX
) {
19708 delta
= event
.originalEvent
.deltaX
;
19711 // Non-standard events
19712 if ( !this.sawWheelEvent
) {
19713 if ( event
.originalEvent
.wheelDeltaX
) {
19714 delta
= -event
.originalEvent
.wheelDeltaX
;
19715 } else if ( event
.originalEvent
.wheelDeltaY
) {
19716 delta
= event
.originalEvent
.wheelDeltaY
;
19717 } else if ( event
.originalEvent
.wheelDelta
) {
19718 delta
= event
.originalEvent
.wheelDelta
;
19719 } else if ( event
.originalEvent
.detail
) {
19720 delta
= -event
.originalEvent
.detail
;
19725 delta
= delta
< 0 ? -1 : 1;
19726 this.adjustValue( delta
* this.step
);
19733 * Handle key down events.
19736 * @param {jQuery.Event} e Key down event
19738 OO
.ui
.NumberInputWidget
.prototype.onKeyDown = function ( e
) {
19739 if ( !this.isDisabled() ) {
19740 switch ( e
.which
) {
19741 case OO
.ui
.Keys
.UP
:
19742 this.adjustValue( this.step
);
19744 case OO
.ui
.Keys
.DOWN
:
19745 this.adjustValue( -this.step
);
19747 case OO
.ui
.Keys
.PAGEUP
:
19748 this.adjustValue( this.pageStep
);
19750 case OO
.ui
.Keys
.PAGEDOWN
:
19751 this.adjustValue( -this.pageStep
);
19760 OO
.ui
.NumberInputWidget
.prototype.setDisabled = function ( disabled
) {
19762 OO
.ui
.NumberInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
19764 if ( this.input
) {
19765 this.input
.setDisabled( this.isDisabled() );
19767 if ( this.minusButton
) {
19768 this.minusButton
.setDisabled( this.isDisabled() );
19770 if ( this.plusButton
) {
19771 this.plusButton
.setDisabled( this.isDisabled() );
19778 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
19779 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
19780 * visually by a slider in the leftmost position.
19783 * // Toggle switches in the 'off' and 'on' position.
19784 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
19785 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
19789 * // Create a FieldsetLayout to layout and label switches
19790 * var fieldset = new OO.ui.FieldsetLayout( {
19791 * label: 'Toggle switches'
19793 * fieldset.addItems( [
19794 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
19795 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
19797 * $( 'body' ).append( fieldset.$element );
19800 * @extends OO.ui.ToggleWidget
19801 * @mixins OO.ui.mixin.TabIndexedElement
19804 * @param {Object} [config] Configuration options
19805 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
19806 * By default, the toggle switch is in the 'off' position.
19808 OO
.ui
.ToggleSwitchWidget
= function OoUiToggleSwitchWidget( config
) {
19809 // Parent constructor
19810 OO
.ui
.ToggleSwitchWidget
.parent
.call( this, config
);
19812 // Mixin constructors
19813 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
19816 this.dragging
= false;
19817 this.dragStart
= null;
19818 this.sliding
= false;
19819 this.$glow
= $( '<span>' );
19820 this.$grip
= $( '<span>' );
19823 this.$element
.on( {
19824 click
: this.onClick
.bind( this ),
19825 keypress
: this.onKeyPress
.bind( this )
19829 this.$glow
.addClass( 'oo-ui-toggleSwitchWidget-glow' );
19830 this.$grip
.addClass( 'oo-ui-toggleSwitchWidget-grip' );
19832 .addClass( 'oo-ui-toggleSwitchWidget' )
19833 .attr( 'role', 'checkbox' )
19834 .append( this.$glow
, this.$grip
);
19839 OO
.inheritClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.ToggleWidget
);
19840 OO
.mixinClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.mixin
.TabIndexedElement
);
19845 * Handle mouse click events.
19848 * @param {jQuery.Event} e Mouse click event
19850 OO
.ui
.ToggleSwitchWidget
.prototype.onClick = function ( e
) {
19851 if ( !this.isDisabled() && e
.which
=== 1 ) {
19852 this.setValue( !this.value
);
19858 * Handle key press events.
19861 * @param {jQuery.Event} e Key press event
19863 OO
.ui
.ToggleSwitchWidget
.prototype.onKeyPress = function ( e
) {
19864 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
19865 this.setValue( !this.value
);