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-10-27T17:52:51Z
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 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
1293 state
= cls
.static.gatherPreInfuseState( $elem
, data
);
1294 // jscs:disable requireCapitalizedConstructors
1295 obj
= new cls( data
); // rebuild widget
1296 // now replace old DOM with this new DOM.
1298 $elem
.replaceWith( obj
.$element
);
1299 // This element is now gone from the DOM, but if anyone is holding a reference to it,
1300 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
1301 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
1302 $elem
[ 0 ].oouiInfused
= obj
;
1305 obj
.$element
.data( 'ooui-infused', obj
);
1306 // set the 'data-ooui' attribute so we can identify infused widgets
1307 obj
.$element
.attr( 'data-ooui', '' );
1308 // restore dynamic state after the new element is inserted into DOM
1309 domPromise
.done( obj
.restorePreInfuseState
.bind( obj
, state
) );
1314 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of a HTML DOM node
1315 * (and its children) that represent an Element of the same class and the given configuration,
1316 * generated by the PHP implementation.
1318 * This method is called just before `node` is detached from the DOM. The return value of this
1319 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
1320 * is inserted into DOM to replace `node`.
1323 * @param {HTMLElement} node
1324 * @param {Object} config
1327 OO
.ui
.Element
.static.gatherPreInfuseState = function () {
1332 * Get a jQuery function within a specific document.
1335 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1336 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1338 * @return {Function} Bound jQuery function
1340 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
1341 function wrapper( selector
) {
1342 return $( selector
, wrapper
.context
);
1345 wrapper
.context
= this.getDocument( context
);
1348 wrapper
.$iframe
= $iframe
;
1355 * Get the document of an element.
1358 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1359 * @return {HTMLDocument|null} Document object
1361 OO
.ui
.Element
.static.getDocument = function ( obj
) {
1362 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1363 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
1364 // Empty jQuery selections might have a context
1367 obj
.ownerDocument
||
1371 ( obj
.nodeType
=== 9 && obj
) ||
1376 * Get the window of an element or document.
1379 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1380 * @return {Window} Window object
1382 OO
.ui
.Element
.static.getWindow = function ( obj
) {
1383 var doc
= this.getDocument( obj
);
1385 // Standard Document.defaultView is IE9+
1386 return doc
.parentWindow
|| doc
.defaultView
;
1390 * Get the direction of an element or document.
1393 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1394 * @return {string} Text direction, either 'ltr' or 'rtl'
1396 OO
.ui
.Element
.static.getDir = function ( obj
) {
1399 if ( obj
instanceof jQuery
) {
1402 isDoc
= obj
.nodeType
=== 9;
1403 isWin
= obj
.document
!== undefined;
1404 if ( isDoc
|| isWin
) {
1410 return $( obj
).css( 'direction' );
1414 * Get the offset between two frames.
1416 * TODO: Make this function not use recursion.
1419 * @param {Window} from Window of the child frame
1420 * @param {Window} [to=window] Window of the parent frame
1421 * @param {Object} [offset] Offset to start with, used internally
1422 * @return {Object} Offset object, containing left and top properties
1424 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
1425 var i
, len
, frames
, frame
, rect
;
1431 offset
= { top
: 0, left
: 0 };
1433 if ( from.parent
=== from ) {
1437 // Get iframe element
1438 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
1439 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
1440 if ( frames
[ i
].contentWindow
=== from ) {
1441 frame
= frames
[ i
];
1446 // Recursively accumulate offset values
1448 rect
= frame
.getBoundingClientRect();
1449 offset
.left
+= rect
.left
;
1450 offset
.top
+= rect
.top
;
1451 if ( from !== to
) {
1452 this.getFrameOffset( from.parent
, offset
);
1459 * Get the offset between two elements.
1461 * The two elements may be in a different frame, but in that case the frame $element is in must
1462 * be contained in the frame $anchor is in.
1465 * @param {jQuery} $element Element whose position to get
1466 * @param {jQuery} $anchor Element to get $element's position relative to
1467 * @return {Object} Translated position coordinates, containing top and left properties
1469 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
1470 var iframe
, iframePos
,
1471 pos
= $element
.offset(),
1472 anchorPos
= $anchor
.offset(),
1473 elementDocument
= this.getDocument( $element
),
1474 anchorDocument
= this.getDocument( $anchor
);
1476 // If $element isn't in the same document as $anchor, traverse up
1477 while ( elementDocument
!== anchorDocument
) {
1478 iframe
= elementDocument
.defaultView
.frameElement
;
1480 throw new Error( '$element frame is not contained in $anchor frame' );
1482 iframePos
= $( iframe
).offset();
1483 pos
.left
+= iframePos
.left
;
1484 pos
.top
+= iframePos
.top
;
1485 elementDocument
= iframe
.ownerDocument
;
1487 pos
.left
-= anchorPos
.left
;
1488 pos
.top
-= anchorPos
.top
;
1493 * Get element border sizes.
1496 * @param {HTMLElement} el Element to measure
1497 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1499 OO
.ui
.Element
.static.getBorders = function ( el
) {
1500 var doc
= el
.ownerDocument
,
1502 // Standard Document.defaultView is IE9+
1503 win
= doc
.parentWindow
|| doc
.defaultView
,
1504 style
= win
&& win
.getComputedStyle
?
1505 win
.getComputedStyle( el
, null ) :
1507 // Standard getComputedStyle() is IE9+
1510 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
1511 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
1512 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
1513 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
1524 * Get dimensions of an element or window.
1527 * @param {HTMLElement|Window} el Element to measure
1528 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1530 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1532 doc
= el
.ownerDocument
|| el
.document
,
1534 // Standard Document.defaultView is IE9+
1535 win
= doc
.parentWindow
|| doc
.defaultView
;
1537 if ( win
=== el
|| el
=== doc
.documentElement
) {
1540 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1542 top
: $win
.scrollTop(),
1543 left
: $win
.scrollLeft()
1545 scrollbar
: { right
: 0, bottom
: 0 },
1549 bottom
: $win
.innerHeight(),
1550 right
: $win
.innerWidth()
1556 borders
: this.getBorders( el
),
1558 top
: $el
.scrollTop(),
1559 left
: $el
.scrollLeft()
1562 right
: $el
.innerWidth() - el
.clientWidth
,
1563 bottom
: $el
.innerHeight() - el
.clientHeight
1565 rect
: el
.getBoundingClientRect()
1571 * Get scrollable object parent
1573 * documentElement can't be used to get or set the scrollTop
1574 * property on Blink. Changing and testing its value lets us
1575 * use 'body' or 'documentElement' based on what is working.
1577 * https://code.google.com/p/chromium/issues/detail?id=303131
1580 * @param {HTMLElement} el Element to find scrollable parent for
1581 * @return {HTMLElement} Scrollable parent
1583 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1584 var scrollTop
, body
;
1586 if ( OO
.ui
.scrollableElement
=== undefined ) {
1587 body
= el
.ownerDocument
.body
;
1588 scrollTop
= body
.scrollTop
;
1591 if ( body
.scrollTop
=== 1 ) {
1592 body
.scrollTop
= scrollTop
;
1593 OO
.ui
.scrollableElement
= 'body';
1595 OO
.ui
.scrollableElement
= 'documentElement';
1599 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1603 * Get closest scrollable container.
1605 * Traverses up until either a scrollable element or the root is reached, in which case the window
1609 * @param {HTMLElement} el Element to find scrollable container for
1610 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1611 * @return {HTMLElement} Closest scrollable container
1613 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1615 // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
1616 props
= [ 'overflow-x', 'overflow-y' ],
1617 $parent
= $( el
).parent();
1619 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1620 props
= [ 'overflow-' + dimension
];
1623 while ( $parent
.length
) {
1624 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1625 return $parent
[ 0 ];
1629 val
= $parent
.css( props
[ i
] );
1630 if ( val
=== 'auto' || val
=== 'scroll' ) {
1631 return $parent
[ 0 ];
1634 $parent
= $parent
.parent();
1636 return this.getDocument( el
).body
;
1640 * Scroll element into view.
1643 * @param {HTMLElement} el Element to scroll into view
1644 * @param {Object} [config] Configuration options
1645 * @param {string} [config.duration] jQuery animation duration value
1646 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1647 * to scroll in both directions
1648 * @param {Function} [config.complete] Function to call when scrolling completes
1650 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1651 var rel
, anim
, callback
, sc
, $sc
, eld
, scd
, $win
;
1653 // Configuration initialization
1654 config
= config
|| {};
1657 callback
= typeof config
.complete
=== 'function' && config
.complete
;
1658 sc
= this.getClosestScrollableContainer( el
, config
.direction
);
1660 eld
= this.getDimensions( el
);
1661 scd
= this.getDimensions( sc
);
1662 $win
= $( this.getWindow( el
) );
1664 // Compute the distances between the edges of el and the edges of the scroll viewport
1665 if ( $sc
.is( 'html, body' ) ) {
1666 // If the scrollable container is the root, this is easy
1669 bottom
: $win
.innerHeight() - eld
.rect
.bottom
,
1670 left
: eld
.rect
.left
,
1671 right
: $win
.innerWidth() - eld
.rect
.right
1674 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1676 top
: eld
.rect
.top
- ( scd
.rect
.top
+ scd
.borders
.top
),
1677 bottom
: scd
.rect
.bottom
- scd
.borders
.bottom
- scd
.scrollbar
.bottom
- eld
.rect
.bottom
,
1678 left
: eld
.rect
.left
- ( scd
.rect
.left
+ scd
.borders
.left
),
1679 right
: scd
.rect
.right
- scd
.borders
.right
- scd
.scrollbar
.right
- eld
.rect
.right
1683 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1684 if ( rel
.top
< 0 ) {
1685 anim
.scrollTop
= scd
.scroll
.top
+ rel
.top
;
1686 } else if ( rel
.top
> 0 && rel
.bottom
< 0 ) {
1687 anim
.scrollTop
= scd
.scroll
.top
+ Math
.min( rel
.top
, -rel
.bottom
);
1690 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1691 if ( rel
.left
< 0 ) {
1692 anim
.scrollLeft
= scd
.scroll
.left
+ rel
.left
;
1693 } else if ( rel
.left
> 0 && rel
.right
< 0 ) {
1694 anim
.scrollLeft
= scd
.scroll
.left
+ Math
.min( rel
.left
, -rel
.right
);
1697 if ( !$.isEmptyObject( anim
) ) {
1698 $sc
.stop( true ).animate( anim
, config
.duration
|| 'fast' );
1700 $sc
.queue( function ( next
) {
1713 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1714 * and reserve space for them, because it probably doesn't.
1716 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1717 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1718 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1719 * and then reattach (or show) them back.
1722 * @param {HTMLElement} el Element to reconsider the scrollbars on
1724 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1725 var i
, len
, scrollLeft
, scrollTop
, nodes
= [];
1726 // Save scroll position
1727 scrollLeft
= el
.scrollLeft
;
1728 scrollTop
= el
.scrollTop
;
1729 // Detach all children
1730 while ( el
.firstChild
) {
1731 nodes
.push( el
.firstChild
);
1732 el
.removeChild( el
.firstChild
);
1735 void el
.offsetHeight
;
1736 // Reattach all children
1737 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1738 el
.appendChild( nodes
[ i
] );
1740 // Restore scroll position (no-op if scrollbars disappeared)
1741 el
.scrollLeft
= scrollLeft
;
1742 el
.scrollTop
= scrollTop
;
1748 * Toggle visibility of an element.
1750 * @param {boolean} [show] Make element visible, omit to toggle visibility
1754 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1755 show
= show
=== undefined ? !this.visible
: !!show
;
1757 if ( show
!== this.isVisible() ) {
1758 this.visible
= show
;
1759 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1760 this.emit( 'toggle', show
);
1767 * Check if element is visible.
1769 * @return {boolean} element is visible
1771 OO
.ui
.Element
.prototype.isVisible = function () {
1772 return this.visible
;
1778 * @return {Mixed} Element data
1780 OO
.ui
.Element
.prototype.getData = function () {
1787 * @param {Mixed} Element data
1790 OO
.ui
.Element
.prototype.setData = function ( data
) {
1796 * Check if element supports one or more methods.
1798 * @param {string|string[]} methods Method or list of methods to check
1799 * @return {boolean} All methods are supported
1801 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1805 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1806 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1807 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1812 return methods
.length
=== support
;
1816 * Update the theme-provided classes.
1818 * @localdoc This is called in element mixins and widget classes any time state changes.
1819 * Updating is debounced, minimizing overhead of changing multiple attributes and
1820 * guaranteeing that theme updates do not occur within an element's constructor
1822 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1823 this.debouncedUpdateThemeClassesHandler();
1828 * @localdoc This method is called directly from the QUnit tests instead of #updateThemeClasses, to
1829 * make them synchronous.
1831 OO
.ui
.Element
.prototype.debouncedUpdateThemeClasses = function () {
1832 OO
.ui
.theme
.updateElementClasses( this );
1836 * Get the HTML tag name.
1838 * Override this method to base the result on instance information.
1840 * @return {string} HTML tag name
1842 OO
.ui
.Element
.prototype.getTagName = function () {
1843 return this.constructor.static.tagName
;
1847 * Check if the element is attached to the DOM
1848 * @return {boolean} The element is attached to the DOM
1850 OO
.ui
.Element
.prototype.isElementAttached = function () {
1851 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1855 * Get the DOM document.
1857 * @return {HTMLDocument} Document object
1859 OO
.ui
.Element
.prototype.getElementDocument = function () {
1860 // Don't cache this in other ways either because subclasses could can change this.$element
1861 return OO
.ui
.Element
.static.getDocument( this.$element
);
1865 * Get the DOM window.
1867 * @return {Window} Window object
1869 OO
.ui
.Element
.prototype.getElementWindow = function () {
1870 return OO
.ui
.Element
.static.getWindow( this.$element
);
1874 * Get closest scrollable container.
1876 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1877 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1881 * Get group element is in.
1883 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1885 OO
.ui
.Element
.prototype.getElementGroup = function () {
1886 return this.elementGroup
;
1890 * Set group element is in.
1892 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1895 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1896 this.elementGroup
= group
;
1901 * Scroll element into view.
1903 * @param {Object} [config] Configuration options
1905 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1906 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1910 * Restore the pre-infusion dynamic state for this widget.
1912 * This method is called after #$element has been inserted into DOM. The parameter is the return
1913 * value of #gatherPreInfuseState.
1916 * @param {Object} state
1918 OO
.ui
.Element
.prototype.restorePreInfuseState = function () {
1922 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1923 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1924 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1925 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1926 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1930 * @extends OO.ui.Element
1931 * @mixins OO.EventEmitter
1934 * @param {Object} [config] Configuration options
1936 OO
.ui
.Layout
= function OoUiLayout( config
) {
1937 // Configuration initialization
1938 config
= config
|| {};
1940 // Parent constructor
1941 OO
.ui
.Layout
.parent
.call( this, config
);
1943 // Mixin constructors
1944 OO
.EventEmitter
.call( this );
1947 this.$element
.addClass( 'oo-ui-layout' );
1952 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1953 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1956 * Widgets are compositions of one or more OOjs UI elements that users can both view
1957 * and interact with. All widgets can be configured and modified via a standard API,
1958 * and their state can change dynamically according to a model.
1962 * @extends OO.ui.Element
1963 * @mixins OO.EventEmitter
1966 * @param {Object} [config] Configuration options
1967 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1968 * appearance reflects this state.
1970 OO
.ui
.Widget
= function OoUiWidget( config
) {
1971 // Initialize config
1972 config
= $.extend( { disabled
: false }, config
);
1974 // Parent constructor
1975 OO
.ui
.Widget
.parent
.call( this, config
);
1977 // Mixin constructors
1978 OO
.EventEmitter
.call( this );
1981 this.disabled
= null;
1982 this.wasDisabled
= null;
1985 this.$element
.addClass( 'oo-ui-widget' );
1986 this.setDisabled( !!config
.disabled
);
1991 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1992 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1994 /* Static Properties */
1997 * Whether this widget will behave reasonably when wrapped in a HTML `<label>`. If this is true,
1998 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
2003 * @property {boolean}
2005 OO
.ui
.Widget
.static.supportsSimpleLabel
= false;
2012 * A 'disable' event is emitted when the disabled state of the widget changes
2013 * (i.e. on disable **and** enable).
2015 * @param {boolean} disabled Widget is disabled
2021 * A 'toggle' event is emitted when the visibility of the widget changes.
2023 * @param {boolean} visible Widget is visible
2029 * Check if the widget is disabled.
2031 * @return {boolean} Widget is disabled
2033 OO
.ui
.Widget
.prototype.isDisabled = function () {
2034 return this.disabled
;
2038 * Set the 'disabled' state of the widget.
2040 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
2042 * @param {boolean} disabled Disable widget
2045 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
2048 this.disabled
= !!disabled
;
2049 isDisabled
= this.isDisabled();
2050 if ( isDisabled
!== this.wasDisabled
) {
2051 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
2052 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
2053 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
2054 this.emit( 'disable', isDisabled
);
2055 this.updateThemeClasses();
2057 this.wasDisabled
= isDisabled
;
2063 * Update the disabled state, in case of changes in parent widget.
2067 OO
.ui
.Widget
.prototype.updateDisabled = function () {
2068 this.setDisabled( this.disabled
);
2073 * A window is a container for elements that are in a child frame. They are used with
2074 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
2075 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
2076 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
2077 * the window manager will choose a sensible fallback.
2079 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
2080 * different processes are executed:
2082 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
2083 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
2086 * - {@link #getSetupProcess} method is called and its result executed
2087 * - {@link #getReadyProcess} method is called and its result executed
2089 * **opened**: The window is now open
2091 * **closing**: The closing stage begins when the window manager's
2092 * {@link OO.ui.WindowManager#closeWindow closeWindow}
2093 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
2095 * - {@link #getHoldProcess} method is called and its result executed
2096 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
2098 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
2099 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
2100 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
2101 * processing can complete. Always assume window processes are executed asynchronously.
2103 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2105 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
2109 * @extends OO.ui.Element
2110 * @mixins OO.EventEmitter
2113 * @param {Object} [config] Configuration options
2114 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
2115 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
2117 OO
.ui
.Window
= function OoUiWindow( config
) {
2118 // Configuration initialization
2119 config
= config
|| {};
2121 // Parent constructor
2122 OO
.ui
.Window
.parent
.call( this, config
);
2124 // Mixin constructors
2125 OO
.EventEmitter
.call( this );
2128 this.manager
= null;
2129 this.size
= config
.size
|| this.constructor.static.size
;
2130 this.$frame
= $( '<div>' );
2131 this.$overlay
= $( '<div>' );
2132 this.$content
= $( '<div>' );
2134 this.$focusTrapBefore
= $( '<div>' ).prop( 'tabIndex', 0 );
2135 this.$focusTrapAfter
= $( '<div>' ).prop( 'tabIndex', 0 );
2136 this.$focusTraps
= this.$focusTrapBefore
.add( this.$focusTrapAfter
);
2139 this.$overlay
.addClass( 'oo-ui-window-overlay' );
2141 .addClass( 'oo-ui-window-content' )
2142 .attr( 'tabindex', 0 );
2144 .addClass( 'oo-ui-window-frame' )
2145 .append( this.$focusTrapBefore
, this.$content
, this.$focusTrapAfter
);
2148 .addClass( 'oo-ui-window' )
2149 .append( this.$frame
, this.$overlay
);
2151 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
2152 // that reference properties not initialized at that time of parent class construction
2153 // TODO: Find a better way to handle post-constructor setup
2154 this.visible
= false;
2155 this.$element
.addClass( 'oo-ui-element-hidden' );
2160 OO
.inheritClass( OO
.ui
.Window
, OO
.ui
.Element
);
2161 OO
.mixinClass( OO
.ui
.Window
, OO
.EventEmitter
);
2163 /* Static Properties */
2166 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
2168 * The static size is used if no #size is configured during construction.
2172 * @property {string}
2174 OO
.ui
.Window
.static.size
= 'medium';
2179 * Handle mouse down events.
2182 * @param {jQuery.Event} e Mouse down event
2184 OO
.ui
.Window
.prototype.onMouseDown = function ( e
) {
2185 // Prevent clicking on the click-block from stealing focus
2186 if ( e
.target
=== this.$element
[ 0 ] ) {
2192 * Check if the window has been initialized.
2194 * Initialization occurs when a window is added to a manager.
2196 * @return {boolean} Window has been initialized
2198 OO
.ui
.Window
.prototype.isInitialized = function () {
2199 return !!this.manager
;
2203 * Check if the window is visible.
2205 * @return {boolean} Window is visible
2207 OO
.ui
.Window
.prototype.isVisible = function () {
2208 return this.visible
;
2212 * Check if the window is opening.
2214 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
2217 * @return {boolean} Window is opening
2219 OO
.ui
.Window
.prototype.isOpening = function () {
2220 return this.manager
.isOpening( this );
2224 * Check if the window is closing.
2226 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
2228 * @return {boolean} Window is closing
2230 OO
.ui
.Window
.prototype.isClosing = function () {
2231 return this.manager
.isClosing( this );
2235 * Check if the window is opened.
2237 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
2239 * @return {boolean} Window is opened
2241 OO
.ui
.Window
.prototype.isOpened = function () {
2242 return this.manager
.isOpened( this );
2246 * Get the window manager.
2248 * All windows must be attached to a window manager, which is used to open
2249 * and close the window and control its presentation.
2251 * @return {OO.ui.WindowManager} Manager of window
2253 OO
.ui
.Window
.prototype.getManager = function () {
2254 return this.manager
;
2258 * Get the symbolic name of the window size (e.g., `small` or `medium`).
2260 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
2262 OO
.ui
.Window
.prototype.getSize = function () {
2263 var viewport
= OO
.ui
.Element
.static.getDimensions( this.getElementWindow() ),
2264 sizes
= this.manager
.constructor.static.sizes
,
2267 if ( !sizes
[ size
] ) {
2268 size
= this.manager
.constructor.static.defaultSize
;
2270 if ( size
!== 'full' && viewport
.rect
.right
- viewport
.rect
.left
< sizes
[ size
].width
) {
2278 * Get the size properties associated with the current window size
2280 * @return {Object} Size properties
2282 OO
.ui
.Window
.prototype.getSizeProperties = function () {
2283 return this.manager
.constructor.static.sizes
[ this.getSize() ];
2287 * Disable transitions on window's frame for the duration of the callback function, then enable them
2291 * @param {Function} callback Function to call while transitions are disabled
2293 OO
.ui
.Window
.prototype.withoutSizeTransitions = function ( callback
) {
2294 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2295 // Disable transitions first, otherwise we'll get values from when the window was animating.
2297 styleObj
= this.$frame
[ 0 ].style
;
2298 oldTransition
= styleObj
.transition
|| styleObj
.OTransition
|| styleObj
.MsTransition
||
2299 styleObj
.MozTransition
|| styleObj
.WebkitTransition
;
2300 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
2301 styleObj
.MozTransition
= styleObj
.WebkitTransition
= 'none';
2303 // Force reflow to make sure the style changes done inside callback really are not transitioned
2304 this.$frame
.height();
2305 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
2306 styleObj
.MozTransition
= styleObj
.WebkitTransition
= oldTransition
;
2310 * Get the height of the full window contents (i.e., the window head, body and foot together).
2312 * What consistitutes the head, body, and foot varies depending on the window type.
2313 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
2314 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
2315 * and special actions in the head, and dialog content in the body.
2317 * To get just the height of the dialog body, use the #getBodyHeight method.
2319 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
2321 OO
.ui
.Window
.prototype.getContentHeight = function () {
2324 bodyStyleObj
= this.$body
[ 0 ].style
,
2325 frameStyleObj
= this.$frame
[ 0 ].style
;
2327 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2328 // Disable transitions first, otherwise we'll get values from when the window was animating.
2329 this.withoutSizeTransitions( function () {
2330 var oldHeight
= frameStyleObj
.height
,
2331 oldPosition
= bodyStyleObj
.position
;
2332 frameStyleObj
.height
= '1px';
2333 // Force body to resize to new width
2334 bodyStyleObj
.position
= 'relative';
2335 bodyHeight
= win
.getBodyHeight();
2336 frameStyleObj
.height
= oldHeight
;
2337 bodyStyleObj
.position
= oldPosition
;
2341 // Add buffer for border
2342 ( this.$frame
.outerHeight() - this.$frame
.innerHeight() ) +
2343 // Use combined heights of children
2344 ( this.$head
.outerHeight( true ) + bodyHeight
+ this.$foot
.outerHeight( true ) )
2349 * Get the height of the window body.
2351 * To get the height of the full window contents (the window body, head, and foot together),
2352 * use #getContentHeight.
2354 * When this function is called, the window will temporarily have been resized
2355 * to height=1px, so .scrollHeight measurements can be taken accurately.
2357 * @return {number} Height of the window body in pixels
2359 OO
.ui
.Window
.prototype.getBodyHeight = function () {
2360 return this.$body
[ 0 ].scrollHeight
;
2364 * Get the directionality of the frame (right-to-left or left-to-right).
2366 * @return {string} Directionality: `'ltr'` or `'rtl'`
2368 OO
.ui
.Window
.prototype.getDir = function () {
2369 return OO
.ui
.Element
.static.getDir( this.$content
) || 'ltr';
2373 * Get the 'setup' process.
2375 * The setup process is used to set up a window for use in a particular context,
2376 * based on the `data` argument. This method is called during the opening phase of the window’s
2379 * Override this method to add additional steps to the ‘setup’ process the parent method provides
2380 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2383 * To add window content that persists between openings, you may wish to use the #initialize method
2387 * @param {Object} [data] Window opening data
2388 * @return {OO.ui.Process} Setup process
2390 OO
.ui
.Window
.prototype.getSetupProcess = function () {
2391 return new OO
.ui
.Process();
2395 * Get the ‘ready’ process.
2397 * The ready process is used to ready a window for use in a particular
2398 * context, based on the `data` argument. This method is called during the opening phase of
2399 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2401 * Override this method to add additional steps to the ‘ready’ process the parent method
2402 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2403 * methods of OO.ui.Process.
2406 * @param {Object} [data] Window opening data
2407 * @return {OO.ui.Process} Ready process
2409 OO
.ui
.Window
.prototype.getReadyProcess = function () {
2410 return new OO
.ui
.Process();
2414 * Get the 'hold' process.
2416 * The hold proccess is used to keep a window from being used in a particular context,
2417 * based on the `data` argument. This method is called during the closing phase of the window’s
2420 * Override this method to add additional steps to the 'hold' process the parent method provides
2421 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2425 * @param {Object} [data] Window closing data
2426 * @return {OO.ui.Process} Hold process
2428 OO
.ui
.Window
.prototype.getHoldProcess = function () {
2429 return new OO
.ui
.Process();
2433 * Get the ‘teardown’ process.
2435 * The teardown process is used to teardown a window after use. During teardown,
2436 * user interactions within the window are conveyed and the window is closed, based on the `data`
2437 * argument. This method is called during the closing phase of the window’s lifecycle.
2439 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2440 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2444 * @param {Object} [data] Window closing data
2445 * @return {OO.ui.Process} Teardown process
2447 OO
.ui
.Window
.prototype.getTeardownProcess = function () {
2448 return new OO
.ui
.Process();
2452 * Set the window manager.
2454 * This will cause the window to initialize. Calling it more than once will cause an error.
2456 * @param {OO.ui.WindowManager} manager Manager for this window
2457 * @throws {Error} An error is thrown if the method is called more than once
2460 OO
.ui
.Window
.prototype.setManager = function ( manager
) {
2461 if ( this.manager
) {
2462 throw new Error( 'Cannot set window manager, window already has a manager' );
2465 this.manager
= manager
;
2472 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2474 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2478 OO
.ui
.Window
.prototype.setSize = function ( size
) {
2485 * Update the window size.
2487 * @throws {Error} An error is thrown if the window is not attached to a window manager
2490 OO
.ui
.Window
.prototype.updateSize = function () {
2491 if ( !this.manager
) {
2492 throw new Error( 'Cannot update window size, must be attached to a manager' );
2495 this.manager
.updateWindowSize( this );
2501 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2502 * when the window is opening. In general, setDimensions should not be called directly.
2504 * To set the size of the window, use the #setSize method.
2506 * @param {Object} dim CSS dimension properties
2507 * @param {string|number} [dim.width] Width
2508 * @param {string|number} [dim.minWidth] Minimum width
2509 * @param {string|number} [dim.maxWidth] Maximum width
2510 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2511 * @param {string|number} [dim.minWidth] Minimum height
2512 * @param {string|number} [dim.maxWidth] Maximum height
2515 OO
.ui
.Window
.prototype.setDimensions = function ( dim
) {
2518 styleObj
= this.$frame
[ 0 ].style
;
2520 // Calculate the height we need to set using the correct width
2521 if ( dim
.height
=== undefined ) {
2522 this.withoutSizeTransitions( function () {
2523 var oldWidth
= styleObj
.width
;
2524 win
.$frame
.css( 'width', dim
.width
|| '' );
2525 height
= win
.getContentHeight();
2526 styleObj
.width
= oldWidth
;
2529 height
= dim
.height
;
2533 width
: dim
.width
|| '',
2534 minWidth
: dim
.minWidth
|| '',
2535 maxWidth
: dim
.maxWidth
|| '',
2536 height
: height
|| '',
2537 minHeight
: dim
.minHeight
|| '',
2538 maxHeight
: dim
.maxHeight
|| ''
2545 * Initialize window contents.
2547 * Before the window is opened for the first time, #initialize is called so that content that
2548 * persists between openings can be added to the window.
2550 * To set up a window with new content each time the window opens, use #getSetupProcess.
2552 * @throws {Error} An error is thrown if the window is not attached to a window manager
2555 OO
.ui
.Window
.prototype.initialize = function () {
2556 if ( !this.manager
) {
2557 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2561 this.$head
= $( '<div>' );
2562 this.$body
= $( '<div>' );
2563 this.$foot
= $( '<div>' );
2564 this.$document
= $( this.getElementDocument() );
2567 this.$element
.on( 'mousedown', this.onMouseDown
.bind( this ) );
2570 this.$head
.addClass( 'oo-ui-window-head' );
2571 this.$body
.addClass( 'oo-ui-window-body' );
2572 this.$foot
.addClass( 'oo-ui-window-foot' );
2573 this.$content
.append( this.$head
, this.$body
, this.$foot
);
2579 * Called when someone tries to focus the hidden element at the end of the dialog.
2580 * Sends focus back to the start of the dialog.
2582 * @param {jQuery.Event} event Focus event
2584 OO
.ui
.Window
.prototype.onFocusTrapFocused = function ( event
) {
2585 if ( this.$focusTrapBefore
.is( event
.target
) ) {
2586 OO
.ui
.findFocusable( this.$content
, true ).focus();
2588 // this.$content is the part of the focus cycle, and is the first focusable element
2589 this.$content
.focus();
2596 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2597 * method, which returns a promise resolved when the window is done opening.
2599 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2601 * @param {Object} [data] Window opening data
2602 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2603 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2604 * value is a new promise, which is resolved when the window begins closing.
2605 * @throws {Error} An error is thrown if the window is not attached to a window manager
2607 OO
.ui
.Window
.prototype.open = function ( data
) {
2608 if ( !this.manager
) {
2609 throw new Error( 'Cannot open window, must be attached to a manager' );
2612 return this.manager
.openWindow( this, data
);
2618 * This method is a wrapper around a call to the window
2619 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2620 * which returns a closing promise resolved when the window is done closing.
2622 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2623 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2624 * the window closes.
2626 * @param {Object} [data] Window closing data
2627 * @return {jQuery.Promise} Promise resolved when window is closed
2628 * @throws {Error} An error is thrown if the window is not attached to a window manager
2630 OO
.ui
.Window
.prototype.close = function ( data
) {
2631 if ( !this.manager
) {
2632 throw new Error( 'Cannot close window, must be attached to a manager' );
2635 return this.manager
.closeWindow( this, data
);
2641 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2644 * @param {Object} [data] Window opening data
2645 * @return {jQuery.Promise} Promise resolved when window is setup
2647 OO
.ui
.Window
.prototype.setup = function ( data
) {
2649 deferred
= $.Deferred();
2651 this.toggle( true );
2653 this.focusTrapHandler
= OO
.ui
.bind( this.onFocusTrapFocused
, this );
2654 this.$focusTraps
.on( 'focus', this.focusTrapHandler
);
2656 this.getSetupProcess( data
).execute().done( function () {
2657 // Force redraw by asking the browser to measure the elements' widths
2658 win
.$element
.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2659 win
.$content
.addClass( 'oo-ui-window-content-setup' ).width();
2663 return deferred
.promise();
2669 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2672 * @param {Object} [data] Window opening data
2673 * @return {jQuery.Promise} Promise resolved when window is ready
2675 OO
.ui
.Window
.prototype.ready = function ( data
) {
2677 deferred
= $.Deferred();
2679 this.$content
.focus();
2680 this.getReadyProcess( data
).execute().done( function () {
2681 // Force redraw by asking the browser to measure the elements' widths
2682 win
.$element
.addClass( 'oo-ui-window-ready' ).width();
2683 win
.$content
.addClass( 'oo-ui-window-content-ready' ).width();
2687 return deferred
.promise();
2693 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2696 * @param {Object} [data] Window closing data
2697 * @return {jQuery.Promise} Promise resolved when window is held
2699 OO
.ui
.Window
.prototype.hold = function ( data
) {
2701 deferred
= $.Deferred();
2703 this.getHoldProcess( data
).execute().done( function () {
2704 // Get the focused element within the window's content
2705 var $focus
= win
.$content
.find( OO
.ui
.Element
.static.getDocument( win
.$content
).activeElement
);
2707 // Blur the focused element
2708 if ( $focus
.length
) {
2712 // Force redraw by asking the browser to measure the elements' widths
2713 win
.$element
.removeClass( 'oo-ui-window-ready' ).width();
2714 win
.$content
.removeClass( 'oo-ui-window-content-ready' ).width();
2718 return deferred
.promise();
2724 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2727 * @param {Object} [data] Window closing data
2728 * @return {jQuery.Promise} Promise resolved when window is torn down
2730 OO
.ui
.Window
.prototype.teardown = function ( data
) {
2733 return this.getTeardownProcess( data
).execute()
2734 .done( function () {
2735 // Force redraw by asking the browser to measure the elements' widths
2736 win
.$element
.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2737 win
.$content
.removeClass( 'oo-ui-window-content-setup' ).width();
2738 win
.$focusTraps
.off( 'focus', win
.focusTrapHandler
);
2739 win
.toggle( false );
2744 * The Dialog class serves as the base class for the other types of dialogs.
2745 * Unless extended to include controls, the rendered dialog box is a simple window
2746 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2747 * which opens, closes, and controls the presentation of the window. See the
2748 * [OOjs UI documentation on MediaWiki] [1] for more information.
2751 * // A simple dialog window.
2752 * function MyDialog( config ) {
2753 * MyDialog.parent.call( this, config );
2755 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2756 * MyDialog.prototype.initialize = function () {
2757 * MyDialog.parent.prototype.initialize.call( this );
2758 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2759 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2760 * this.$body.append( this.content.$element );
2762 * MyDialog.prototype.getBodyHeight = function () {
2763 * return this.content.$element.outerHeight( true );
2765 * var myDialog = new MyDialog( {
2768 * // Create and append a window manager, which opens and closes the window.
2769 * var windowManager = new OO.ui.WindowManager();
2770 * $( 'body' ).append( windowManager.$element );
2771 * windowManager.addWindows( [ myDialog ] );
2772 * // Open the window!
2773 * windowManager.openWindow( myDialog );
2775 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2779 * @extends OO.ui.Window
2780 * @mixins OO.ui.mixin.PendingElement
2783 * @param {Object} [config] Configuration options
2785 OO
.ui
.Dialog
= function OoUiDialog( config
) {
2786 // Parent constructor
2787 OO
.ui
.Dialog
.parent
.call( this, config
);
2789 // Mixin constructors
2790 OO
.ui
.mixin
.PendingElement
.call( this );
2793 this.actions
= new OO
.ui
.ActionSet();
2794 this.attachedActions
= [];
2795 this.currentAction
= null;
2796 this.onDialogKeyDownHandler
= this.onDialogKeyDown
.bind( this );
2799 this.actions
.connect( this, {
2800 click
: 'onActionClick',
2801 resize
: 'onActionResize',
2802 change
: 'onActionsChange'
2807 .addClass( 'oo-ui-dialog' )
2808 .attr( 'role', 'dialog' );
2813 OO
.inheritClass( OO
.ui
.Dialog
, OO
.ui
.Window
);
2814 OO
.mixinClass( OO
.ui
.Dialog
, OO
.ui
.mixin
.PendingElement
);
2816 /* Static Properties */
2819 * Symbolic name of dialog.
2821 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2822 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2824 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2829 * @property {string}
2831 OO
.ui
.Dialog
.static.name
= '';
2836 * The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function
2837 * that will produce a Label node or string. The title can also be specified with data passed to the
2838 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2843 * @property {jQuery|string|Function}
2845 OO
.ui
.Dialog
.static.title
= '';
2848 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2850 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2851 * value will be overriden.
2853 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2857 * @property {Object[]}
2859 OO
.ui
.Dialog
.static.actions
= [];
2862 * Close the dialog when the 'Esc' key is pressed.
2867 * @property {boolean}
2869 OO
.ui
.Dialog
.static.escapable
= true;
2874 * Handle frame document key down events.
2877 * @param {jQuery.Event} e Key down event
2879 OO
.ui
.Dialog
.prototype.onDialogKeyDown = function ( e
) {
2880 if ( e
.which
=== OO
.ui
.Keys
.ESCAPE
) {
2883 e
.stopPropagation();
2888 * Handle action resized events.
2891 * @param {OO.ui.ActionWidget} action Action that was resized
2893 OO
.ui
.Dialog
.prototype.onActionResize = function () {
2894 // Override in subclass
2898 * Handle action click events.
2901 * @param {OO.ui.ActionWidget} action Action that was clicked
2903 OO
.ui
.Dialog
.prototype.onActionClick = function ( action
) {
2904 if ( !this.isPending() ) {
2905 this.executeAction( action
.getAction() );
2910 * Handle actions change event.
2914 OO
.ui
.Dialog
.prototype.onActionsChange = function () {
2915 this.detachActions();
2916 if ( !this.isClosing() ) {
2917 this.attachActions();
2922 * Get the set of actions used by the dialog.
2924 * @return {OO.ui.ActionSet}
2926 OO
.ui
.Dialog
.prototype.getActions = function () {
2927 return this.actions
;
2931 * Get a process for taking action.
2933 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2934 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2935 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2938 * @param {string} [action] Symbolic name of action
2939 * @return {OO.ui.Process} Action process
2941 OO
.ui
.Dialog
.prototype.getActionProcess = function ( action
) {
2942 return new OO
.ui
.Process()
2943 .next( function () {
2945 // An empty action always closes the dialog without data, which should always be
2946 // safe and make no changes
2955 * @param {Object} [data] Dialog opening data
2956 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2957 * the {@link #static-title static title}
2958 * @param {Object[]} [data.actions] List of configuration options for each
2959 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2961 OO
.ui
.Dialog
.prototype.getSetupProcess = function ( data
) {
2965 return OO
.ui
.Dialog
.parent
.prototype.getSetupProcess
.call( this, data
)
2966 .next( function () {
2967 var config
= this.constructor.static,
2968 actions
= data
.actions
!== undefined ? data
.actions
: config
.actions
;
2970 this.title
.setLabel(
2971 data
.title
!== undefined ? data
.title
: this.constructor.static.title
2973 this.actions
.add( this.getActionWidgets( actions
) );
2975 if ( this.constructor.static.escapable
) {
2976 this.$element
.on( 'keydown', this.onDialogKeyDownHandler
);
2984 OO
.ui
.Dialog
.prototype.getTeardownProcess = function ( data
) {
2986 return OO
.ui
.Dialog
.parent
.prototype.getTeardownProcess
.call( this, data
)
2987 .first( function () {
2988 if ( this.constructor.static.escapable
) {
2989 this.$element
.off( 'keydown', this.onDialogKeyDownHandler
);
2992 this.actions
.clear();
2993 this.currentAction
= null;
3000 OO
.ui
.Dialog
.prototype.initialize = function () {
3004 OO
.ui
.Dialog
.parent
.prototype.initialize
.call( this );
3006 titleId
= OO
.ui
.generateElementId();
3009 this.title
= new OO
.ui
.LabelWidget( {
3014 this.$content
.addClass( 'oo-ui-dialog-content' );
3015 this.$element
.attr( 'aria-labelledby', titleId
);
3016 this.setPendingElement( this.$head
);
3020 * Get action widgets from a list of configs
3022 * @param {Object[]} actions Action widget configs
3023 * @return {OO.ui.ActionWidget[]} Action widgets
3025 OO
.ui
.Dialog
.prototype.getActionWidgets = function ( actions
) {
3026 var i
, len
, widgets
= [];
3027 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
3029 new OO
.ui
.ActionWidget( actions
[ i
] )
3036 * Attach action actions.
3040 OO
.ui
.Dialog
.prototype.attachActions = function () {
3041 // Remember the list of potentially attached actions
3042 this.attachedActions
= this.actions
.get();
3046 * Detach action actions.
3051 OO
.ui
.Dialog
.prototype.detachActions = function () {
3054 // Detach all actions that may have been previously attached
3055 for ( i
= 0, len
= this.attachedActions
.length
; i
< len
; i
++ ) {
3056 this.attachedActions
[ i
].$element
.detach();
3058 this.attachedActions
= [];
3062 * Execute an action.
3064 * @param {string} action Symbolic name of action to execute
3065 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
3067 OO
.ui
.Dialog
.prototype.executeAction = function ( action
) {
3069 this.currentAction
= action
;
3070 return this.getActionProcess( action
).execute()
3071 .always( this.popPending
.bind( this ) );
3075 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
3076 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
3077 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
3078 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
3079 * pertinent data and reused.
3081 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
3082 * `opened`, and `closing`, which represent the primary stages of the cycle:
3084 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
3085 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
3087 * - an `opening` event is emitted with an `opening` promise
3088 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
3089 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
3090 * window and its result executed
3091 * - a `setup` progress notification is emitted from the `opening` promise
3092 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
3093 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
3094 * window and its result executed
3095 * - a `ready` progress notification is emitted from the `opening` promise
3096 * - the `opening` promise is resolved with an `opened` promise
3098 * **Opened**: the window is now open.
3100 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
3101 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
3102 * to close the window.
3104 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
3105 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
3106 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
3107 * window and its result executed
3108 * - a `hold` progress notification is emitted from the `closing` promise
3109 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
3110 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
3111 * window and its result executed
3112 * - a `teardown` progress notification is emitted from the `closing` promise
3113 * - the `closing` promise is resolved. The window is now closed
3115 * See the [OOjs UI documentation on MediaWiki][1] for more information.
3117 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3120 * @extends OO.ui.Element
3121 * @mixins OO.EventEmitter
3124 * @param {Object} [config] Configuration options
3125 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
3126 * Note that window classes that are instantiated with a factory must have
3127 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
3128 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
3130 OO
.ui
.WindowManager
= function OoUiWindowManager( config
) {
3131 // Configuration initialization
3132 config
= config
|| {};
3134 // Parent constructor
3135 OO
.ui
.WindowManager
.parent
.call( this, config
);
3137 // Mixin constructors
3138 OO
.EventEmitter
.call( this );
3141 this.factory
= config
.factory
;
3142 this.modal
= config
.modal
=== undefined || !!config
.modal
;
3144 this.opening
= null;
3146 this.closing
= null;
3147 this.preparingToOpen
= null;
3148 this.preparingToClose
= null;
3149 this.currentWindow
= null;
3150 this.globalEvents
= false;
3151 this.$ariaHidden
= null;
3152 this.onWindowResizeTimeout
= null;
3153 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
3154 this.afterWindowResizeHandler
= this.afterWindowResize
.bind( this );
3158 .addClass( 'oo-ui-windowManager' )
3159 .toggleClass( 'oo-ui-windowManager-modal', this.modal
);
3164 OO
.inheritClass( OO
.ui
.WindowManager
, OO
.ui
.Element
);
3165 OO
.mixinClass( OO
.ui
.WindowManager
, OO
.EventEmitter
);
3170 * An 'opening' event is emitted when the window begins to be opened.
3173 * @param {OO.ui.Window} win Window that's being opened
3174 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
3175 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
3176 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
3177 * @param {Object} data Window opening data
3181 * A 'closing' event is emitted when the window begins to be closed.
3184 * @param {OO.ui.Window} win Window that's being closed
3185 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
3186 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
3187 * processes are complete. When the `closing` promise is resolved, the first argument of its value
3188 * is the closing data.
3189 * @param {Object} data Window closing data
3193 * A 'resize' event is emitted when a window is resized.
3196 * @param {OO.ui.Window} win Window that was resized
3199 /* Static Properties */
3202 * Map of the symbolic name of each window size and its CSS properties.
3206 * @property {Object}
3208 OO
.ui
.WindowManager
.static.sizes
= {
3222 // These can be non-numeric because they are never used in calculations
3229 * Symbolic name of the default window size.
3231 * The default size is used if the window's requested size is not recognized.
3235 * @property {string}
3237 OO
.ui
.WindowManager
.static.defaultSize
= 'medium';
3242 * Handle window resize events.
3245 * @param {jQuery.Event} e Window resize event
3247 OO
.ui
.WindowManager
.prototype.onWindowResize = function () {
3248 clearTimeout( this.onWindowResizeTimeout
);
3249 this.onWindowResizeTimeout
= setTimeout( this.afterWindowResizeHandler
, 200 );
3253 * Handle window resize events.
3256 * @param {jQuery.Event} e Window resize event
3258 OO
.ui
.WindowManager
.prototype.afterWindowResize = function () {
3259 if ( this.currentWindow
) {
3260 this.updateWindowSize( this.currentWindow
);
3265 * Check if window is opening.
3267 * @return {boolean} Window is opening
3269 OO
.ui
.WindowManager
.prototype.isOpening = function ( win
) {
3270 return win
=== this.currentWindow
&& !!this.opening
&& this.opening
.state() === 'pending';
3274 * Check if window is closing.
3276 * @return {boolean} Window is closing
3278 OO
.ui
.WindowManager
.prototype.isClosing = function ( win
) {
3279 return win
=== this.currentWindow
&& !!this.closing
&& this.closing
.state() === 'pending';
3283 * Check if window is opened.
3285 * @return {boolean} Window is opened
3287 OO
.ui
.WindowManager
.prototype.isOpened = function ( win
) {
3288 return win
=== this.currentWindow
&& !!this.opened
&& this.opened
.state() === 'pending';
3292 * Check if a window is being managed.
3294 * @param {OO.ui.Window} win Window to check
3295 * @return {boolean} Window is being managed
3297 OO
.ui
.WindowManager
.prototype.hasWindow = function ( win
) {
3300 for ( name
in this.windows
) {
3301 if ( this.windows
[ name
] === win
) {
3310 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
3312 * @param {OO.ui.Window} win Window being opened
3313 * @param {Object} [data] Window opening data
3314 * @return {number} Milliseconds to wait
3316 OO
.ui
.WindowManager
.prototype.getSetupDelay = function () {
3321 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
3323 * @param {OO.ui.Window} win Window being opened
3324 * @param {Object} [data] Window opening data
3325 * @return {number} Milliseconds to wait
3327 OO
.ui
.WindowManager
.prototype.getReadyDelay = function () {
3332 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
3334 * @param {OO.ui.Window} win Window being closed
3335 * @param {Object} [data] Window closing data
3336 * @return {number} Milliseconds to wait
3338 OO
.ui
.WindowManager
.prototype.getHoldDelay = function () {
3343 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
3344 * executing the ‘teardown’ process.
3346 * @param {OO.ui.Window} win Window being closed
3347 * @param {Object} [data] Window closing data
3348 * @return {number} Milliseconds to wait
3350 OO
.ui
.WindowManager
.prototype.getTeardownDelay = function () {
3351 return this.modal
? 250 : 0;
3355 * Get a window by its symbolic name.
3357 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
3358 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
3359 * for more information about using factories.
3360 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3362 * @param {string} name Symbolic name of the window
3363 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
3364 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
3365 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
3367 OO
.ui
.WindowManager
.prototype.getWindow = function ( name
) {
3368 var deferred
= $.Deferred(),
3369 win
= this.windows
[ name
];
3371 if ( !( win
instanceof OO
.ui
.Window
) ) {
3372 if ( this.factory
) {
3373 if ( !this.factory
.lookup( name
) ) {
3374 deferred
.reject( new OO
.ui
.Error(
3375 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
3378 win
= this.factory
.create( name
);
3379 this.addWindows( [ win
] );
3380 deferred
.resolve( win
);
3383 deferred
.reject( new OO
.ui
.Error(
3384 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
3388 deferred
.resolve( win
);
3391 return deferred
.promise();
3395 * Get current window.
3397 * @return {OO.ui.Window|null} Currently opening/opened/closing window
3399 OO
.ui
.WindowManager
.prototype.getCurrentWindow = function () {
3400 return this.currentWindow
;
3406 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
3407 * @param {Object} [data] Window opening data
3408 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3409 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3412 OO
.ui
.WindowManager
.prototype.openWindow = function ( win
, data
) {
3414 opening
= $.Deferred();
3416 // Argument handling
3417 if ( typeof win
=== 'string' ) {
3418 return this.getWindow( win
).then( function ( win
) {
3419 return manager
.openWindow( win
, data
);
3424 if ( !this.hasWindow( win
) ) {
3425 opening
.reject( new OO
.ui
.Error(
3426 'Cannot open window: window is not attached to manager'
3428 } else if ( this.preparingToOpen
|| this.opening
|| this.opened
) {
3429 opening
.reject( new OO
.ui
.Error(
3430 'Cannot open window: another window is opening or open'
3435 if ( opening
.state() !== 'rejected' ) {
3436 // If a window is currently closing, wait for it to complete
3437 this.preparingToOpen
= $.when( this.closing
);
3438 // Ensure handlers get called after preparingToOpen is set
3439 this.preparingToOpen
.done( function () {
3440 if ( manager
.modal
) {
3441 manager
.toggleGlobalEvents( true );
3442 manager
.toggleAriaIsolation( true );
3444 manager
.currentWindow
= win
;
3445 manager
.opening
= opening
;
3446 manager
.preparingToOpen
= null;
3447 manager
.emit( 'opening', win
, opening
, data
);
3448 setTimeout( function () {
3449 win
.setup( data
).then( function () {
3450 manager
.updateWindowSize( win
);
3451 manager
.opening
.notify( { state
: 'setup' } );
3452 setTimeout( function () {
3453 win
.ready( data
).then( function () {
3454 manager
.opening
.notify( { state
: 'ready' } );
3455 manager
.opening
= null;
3456 manager
.opened
= $.Deferred();
3457 opening
.resolve( manager
.opened
.promise(), data
);
3459 }, manager
.getReadyDelay() );
3461 }, manager
.getSetupDelay() );
3465 return opening
.promise();
3471 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3472 * @param {Object} [data] Window closing data
3473 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3474 * See {@link #event-closing 'closing' event} for more information about closing promises.
3475 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3478 OO
.ui
.WindowManager
.prototype.closeWindow = function ( win
, data
) {
3480 closing
= $.Deferred(),
3483 // Argument handling
3484 if ( typeof win
=== 'string' ) {
3485 win
= this.windows
[ win
];
3486 } else if ( !this.hasWindow( win
) ) {
3492 closing
.reject( new OO
.ui
.Error(
3493 'Cannot close window: window is not attached to manager'
3495 } else if ( win
!== this.currentWindow
) {
3496 closing
.reject( new OO
.ui
.Error(
3497 'Cannot close window: window already closed with different data'
3499 } else if ( this.preparingToClose
|| this.closing
) {
3500 closing
.reject( new OO
.ui
.Error(
3501 'Cannot close window: window already closing with different data'
3506 if ( closing
.state() !== 'rejected' ) {
3507 // If the window is currently opening, close it when it's done
3508 this.preparingToClose
= $.when( this.opening
);
3509 // Ensure handlers get called after preparingToClose is set
3510 this.preparingToClose
.done( function () {
3511 manager
.closing
= closing
;
3512 manager
.preparingToClose
= null;
3513 manager
.emit( 'closing', win
, closing
, data
);
3514 opened
= manager
.opened
;
3515 manager
.opened
= null;
3516 opened
.resolve( closing
.promise(), data
);
3517 setTimeout( function () {
3518 win
.hold( data
).then( function () {
3519 closing
.notify( { state
: 'hold' } );
3520 setTimeout( function () {
3521 win
.teardown( data
).then( function () {
3522 closing
.notify( { state
: 'teardown' } );
3523 if ( manager
.modal
) {
3524 manager
.toggleGlobalEvents( false );
3525 manager
.toggleAriaIsolation( false );
3527 manager
.closing
= null;
3528 manager
.currentWindow
= null;
3529 closing
.resolve( data
);
3531 }, manager
.getTeardownDelay() );
3533 }, manager
.getHoldDelay() );
3537 return closing
.promise();
3541 * Add windows to the window manager.
3543 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3544 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3545 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3547 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3548 * by reference, symbolic name, or explicitly defined symbolic names.
3549 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3550 * explicit nor a statically configured symbolic name.
3552 OO
.ui
.WindowManager
.prototype.addWindows = function ( windows
) {
3553 var i
, len
, win
, name
, list
;
3555 if ( Array
.isArray( windows
) ) {
3556 // Convert to map of windows by looking up symbolic names from static configuration
3558 for ( i
= 0, len
= windows
.length
; i
< len
; i
++ ) {
3559 name
= windows
[ i
].constructor.static.name
;
3560 if ( typeof name
!== 'string' ) {
3561 throw new Error( 'Cannot add window' );
3563 list
[ name
] = windows
[ i
];
3565 } else if ( OO
.isPlainObject( windows
) ) {
3570 for ( name
in list
) {
3572 this.windows
[ name
] = win
.toggle( false );
3573 this.$element
.append( win
.$element
);
3574 win
.setManager( this );
3579 * Remove the specified windows from the windows manager.
3581 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3582 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3583 * longer listens to events, use the #destroy method.
3585 * @param {string[]} names Symbolic names of windows to remove
3586 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3587 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3589 OO
.ui
.WindowManager
.prototype.removeWindows = function ( names
) {
3590 var i
, len
, win
, name
, cleanupWindow
,
3593 cleanup = function ( name
, win
) {
3594 delete manager
.windows
[ name
];
3595 win
.$element
.detach();
3598 for ( i
= 0, len
= names
.length
; i
< len
; i
++ ) {
3600 win
= this.windows
[ name
];
3602 throw new Error( 'Cannot remove window' );
3604 cleanupWindow
= cleanup
.bind( null, name
, win
);
3605 promises
.push( this.closeWindow( name
).then( cleanupWindow
, cleanupWindow
) );
3608 return $.when
.apply( $, promises
);
3612 * Remove all windows from the window manager.
3614 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3615 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3616 * To remove just a subset of windows, use the #removeWindows method.
3618 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3620 OO
.ui
.WindowManager
.prototype.clearWindows = function () {
3621 return this.removeWindows( Object
.keys( this.windows
) );
3625 * Set dialog size. In general, this method should not be called directly.
3627 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3631 OO
.ui
.WindowManager
.prototype.updateWindowSize = function ( win
) {
3634 // Bypass for non-current, and thus invisible, windows
3635 if ( win
!== this.currentWindow
) {
3639 isFullscreen
= win
.getSize() === 'full';
3641 this.$element
.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen
);
3642 this.$element
.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen
);
3643 win
.setDimensions( win
.getSizeProperties() );
3645 this.emit( 'resize', win
);
3651 * Bind or unbind global events for scrolling.
3654 * @param {boolean} [on] Bind global events
3657 OO
.ui
.WindowManager
.prototype.toggleGlobalEvents = function ( on
) {
3658 var scrollWidth
, bodyMargin
,
3659 $body
= $( this.getElementDocument().body
),
3660 // We could have multiple window managers open so only modify
3661 // the body css at the bottom of the stack
3662 stackDepth
= $body
.data( 'windowManagerGlobalEvents' ) || 0 ;
3664 on
= on
=== undefined ? !!this.globalEvents
: !!on
;
3667 if ( !this.globalEvents
) {
3668 $( this.getElementWindow() ).on( {
3669 // Start listening for top-level window dimension changes
3670 'orientationchange resize': this.onWindowResizeHandler
3672 if ( stackDepth
=== 0 ) {
3673 scrollWidth
= window
.innerWidth
- document
.documentElement
.clientWidth
;
3674 bodyMargin
= parseFloat( $body
.css( 'margin-right' ) ) || 0;
3677 'margin-right': bodyMargin
+ scrollWidth
3681 this.globalEvents
= true;
3683 } else if ( this.globalEvents
) {
3684 $( this.getElementWindow() ).off( {
3685 // Stop listening for top-level window dimension changes
3686 'orientationchange resize': this.onWindowResizeHandler
3689 if ( stackDepth
=== 0 ) {
3695 this.globalEvents
= false;
3697 $body
.data( 'windowManagerGlobalEvents', stackDepth
);
3703 * Toggle screen reader visibility of content other than the window manager.
3706 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3709 OO
.ui
.WindowManager
.prototype.toggleAriaIsolation = function ( isolate
) {
3710 isolate
= isolate
=== undefined ? !this.$ariaHidden
: !!isolate
;
3713 if ( !this.$ariaHidden
) {
3714 // Hide everything other than the window manager from screen readers
3715 this.$ariaHidden
= $( 'body' )
3717 .not( this.$element
.parentsUntil( 'body' ).last() )
3718 .attr( 'aria-hidden', '' );
3720 } else if ( this.$ariaHidden
) {
3721 // Restore screen reader visibility
3722 this.$ariaHidden
.removeAttr( 'aria-hidden' );
3723 this.$ariaHidden
= null;
3730 * Destroy the window manager.
3732 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3733 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3736 OO
.ui
.WindowManager
.prototype.destroy = function () {
3737 this.toggleGlobalEvents( false );
3738 this.toggleAriaIsolation( false );
3739 this.clearWindows();
3740 this.$element
.remove();
3744 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3745 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3746 * appearance and functionality of the error interface.
3748 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3749 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3750 * that initiated the failed process will be disabled.
3752 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3755 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3757 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3762 * @param {string|jQuery} message Description of error
3763 * @param {Object} [config] Configuration options
3764 * @cfg {boolean} [recoverable=true] Error is recoverable.
3765 * By default, errors are recoverable, and users can try the process again.
3766 * @cfg {boolean} [warning=false] Error is a warning.
3767 * If the error is a warning, the error interface will include a
3768 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3769 * is not triggered a second time if the user chooses to continue.
3771 OO
.ui
.Error
= function OoUiError( message
, config
) {
3772 // Allow passing positional parameters inside the config object
3773 if ( OO
.isPlainObject( message
) && config
=== undefined ) {
3775 message
= config
.message
;
3778 // Configuration initialization
3779 config
= config
|| {};
3782 this.message
= message
instanceof jQuery
? message
: String( message
);
3783 this.recoverable
= config
.recoverable
=== undefined || !!config
.recoverable
;
3784 this.warning
= !!config
.warning
;
3789 OO
.initClass( OO
.ui
.Error
);
3794 * Check if the error is recoverable.
3796 * If the error is recoverable, users are able to try the process again.
3798 * @return {boolean} Error is recoverable
3800 OO
.ui
.Error
.prototype.isRecoverable = function () {
3801 return this.recoverable
;
3805 * Check if the error is a warning.
3807 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3809 * @return {boolean} Error is warning
3811 OO
.ui
.Error
.prototype.isWarning = function () {
3812 return this.warning
;
3816 * Get error message as DOM nodes.
3818 * @return {jQuery} Error message in DOM nodes
3820 OO
.ui
.Error
.prototype.getMessage = function () {
3821 return this.message
instanceof jQuery
?
3822 this.message
.clone() :
3823 $( '<div>' ).text( this.message
).contents();
3827 * Get the error message text.
3829 * @return {string} Error message
3831 OO
.ui
.Error
.prototype.getMessageText = function () {
3832 return this.message
instanceof jQuery
? this.message
.text() : this.message
;
3836 * Wraps an HTML snippet for use with configuration values which default
3837 * to strings. This bypasses the default html-escaping done to string
3843 * @param {string} [content] HTML content
3845 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
3847 this.content
= content
;
3852 OO
.initClass( OO
.ui
.HtmlSnippet
);
3859 * @return {string} Unchanged HTML snippet.
3861 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
3862 return this.content
;
3866 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3869 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3870 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3871 * or stop if the promise is rejected.
3872 * - **function**: the process will execute the function. The process will stop if the function returns
3873 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3874 * will wait for that number of milliseconds before proceeding.
3876 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3877 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3878 * its remaining steps will not be performed.
3883 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3884 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3885 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3886 * a number or promise.
3887 * @return {Object} Step object, with `callback` and `context` properties
3889 OO
.ui
.Process = function ( step
, context
) {
3894 if ( step
!== undefined ) {
3895 this.next( step
, context
);
3901 OO
.initClass( OO
.ui
.Process
);
3906 * Start the process.
3908 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
3909 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
3910 * and any remaining steps are not performed.
3912 OO
.ui
.Process
.prototype.execute = function () {
3913 var i
, len
, promise
;
3916 * Continue execution.
3919 * @param {Array} step A function and the context it should be called in
3920 * @return {Function} Function that continues the process
3922 function proceed( step
) {
3923 return function () {
3924 // Execute step in the correct context
3926 result
= step
.callback
.call( step
.context
);
3928 if ( result
=== false ) {
3929 // Use rejected promise for boolean false results
3930 return $.Deferred().reject( [] ).promise();
3932 if ( typeof result
=== 'number' ) {
3934 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3936 // Use a delayed promise for numbers, expecting them to be in milliseconds
3937 deferred
= $.Deferred();
3938 setTimeout( deferred
.resolve
, result
);
3939 return deferred
.promise();
3941 if ( result
instanceof OO
.ui
.Error
) {
3942 // Use rejected promise for error
3943 return $.Deferred().reject( [ result
] ).promise();
3945 if ( Array
.isArray( result
) && result
.length
&& result
[ 0 ] instanceof OO
.ui
.Error
) {
3946 // Use rejected promise for list of errors
3947 return $.Deferred().reject( result
).promise();
3949 // Duck-type the object to see if it can produce a promise
3950 if ( result
&& $.isFunction( result
.promise
) ) {
3951 // Use a promise generated from the result
3952 return result
.promise();
3954 // Use resolved promise for other results
3955 return $.Deferred().resolve().promise();
3959 if ( this.steps
.length
) {
3960 // Generate a chain reaction of promises
3961 promise
= proceed( this.steps
[ 0 ] )();
3962 for ( i
= 1, len
= this.steps
.length
; i
< len
; i
++ ) {
3963 promise
= promise
.then( proceed( this.steps
[ i
] ) );
3966 promise
= $.Deferred().resolve().promise();
3973 * Create a process step.
3976 * @param {number|jQuery.Promise|Function} step
3978 * - Number of milliseconds to wait before proceeding
3979 * - Promise that must be resolved before proceeding
3980 * - Function to execute
3981 * - If the function returns a boolean false the process will stop
3982 * - If the function returns a promise, the process will continue to the next
3983 * step when the promise is resolved or stop if the promise is rejected
3984 * - If the function returns a number, the process will wait for that number of
3985 * milliseconds before proceeding
3986 * @param {Object} [context=null] Execution context of the function. The context is
3987 * ignored if the step is a number or promise.
3988 * @return {Object} Step object, with `callback` and `context` properties
3990 OO
.ui
.Process
.prototype.createStep = function ( step
, context
) {
3991 if ( typeof step
=== 'number' || $.isFunction( step
.promise
) ) {
3993 callback: function () {
3999 if ( $.isFunction( step
) ) {
4005 throw new Error( 'Cannot create process step: number, promise or function expected' );
4009 * Add step to the beginning of the process.
4011 * @inheritdoc #createStep
4012 * @return {OO.ui.Process} this
4015 OO
.ui
.Process
.prototype.first = function ( step
, context
) {
4016 this.steps
.unshift( this.createStep( step
, context
) );
4021 * Add step to the end of the process.
4023 * @inheritdoc #createStep
4024 * @return {OO.ui.Process} this
4027 OO
.ui
.Process
.prototype.next = function ( step
, context
) {
4028 this.steps
.push( this.createStep( step
, context
) );
4033 * A ToolFactory creates tools on demand. All tools ({@link OO.ui.Tool Tools}, {@link OO.ui.PopupTool PopupTools},
4034 * and {@link OO.ui.ToolGroupTool ToolGroupTools}) must be registered with a tool factory. Tools are
4035 * registered by their symbolic name. See {@link OO.ui.Toolbar toolbars} for an example.
4037 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4039 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4042 * @extends OO.Factory
4045 OO
.ui
.ToolFactory
= function OoUiToolFactory() {
4046 // Parent constructor
4047 OO
.ui
.ToolFactory
.parent
.call( this );
4052 OO
.inheritClass( OO
.ui
.ToolFactory
, OO
.Factory
);
4057 * Get tools from the factory
4059 * @param {Array} include Included tools
4060 * @param {Array} exclude Excluded tools
4061 * @param {Array} promote Promoted tools
4062 * @param {Array} demote Demoted tools
4063 * @return {string[]} List of tools
4065 OO
.ui
.ToolFactory
.prototype.getTools = function ( include
, exclude
, promote
, demote
) {
4066 var i
, len
, included
, promoted
, demoted
,
4070 // Collect included and not excluded tools
4071 included
= OO
.simpleArrayDifference( this.extract( include
), this.extract( exclude
) );
4074 promoted
= this.extract( promote
, used
);
4075 demoted
= this.extract( demote
, used
);
4078 for ( i
= 0, len
= included
.length
; i
< len
; i
++ ) {
4079 if ( !used
[ included
[ i
] ] ) {
4080 auto
.push( included
[ i
] );
4084 return promoted
.concat( auto
).concat( demoted
);
4088 * Get a flat list of names from a list of names or groups.
4090 * Tools can be specified in the following ways:
4092 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
4093 * - All tools in a group: `{ group: 'group-name' }`
4094 * - All tools: `'*'`
4097 * @param {Array|string} collection List of tools
4098 * @param {Object} [used] Object with names that should be skipped as properties; extracted
4099 * names will be added as properties
4100 * @return {string[]} List of extracted names
4102 OO
.ui
.ToolFactory
.prototype.extract = function ( collection
, used
) {
4103 var i
, len
, item
, name
, tool
,
4106 if ( collection
=== '*' ) {
4107 for ( name
in this.registry
) {
4108 tool
= this.registry
[ name
];
4110 // Only add tools by group name when auto-add is enabled
4111 tool
.static.autoAddToCatchall
&&
4112 // Exclude already used tools
4113 ( !used
|| !used
[ name
] )
4117 used
[ name
] = true;
4121 } else if ( Array
.isArray( collection
) ) {
4122 for ( i
= 0, len
= collection
.length
; i
< len
; i
++ ) {
4123 item
= collection
[ i
];
4124 // Allow plain strings as shorthand for named tools
4125 if ( typeof item
=== 'string' ) {
4126 item
= { name
: item
};
4128 if ( OO
.isPlainObject( item
) ) {
4130 for ( name
in this.registry
) {
4131 tool
= this.registry
[ name
];
4133 // Include tools with matching group
4134 tool
.static.group
=== item
.group
&&
4135 // Only add tools by group name when auto-add is enabled
4136 tool
.static.autoAddToGroup
&&
4137 // Exclude already used tools
4138 ( !used
|| !used
[ name
] )
4142 used
[ name
] = true;
4146 // Include tools with matching name and exclude already used tools
4147 } else if ( item
.name
&& ( !used
|| !used
[ item
.name
] ) ) {
4148 names
.push( item
.name
);
4150 used
[ item
.name
] = true;
4160 * ToolGroupFactories create {@link OO.ui.ToolGroup toolgroups} on demand. The toolgroup classes must
4161 * specify a symbolic name and be registered with the factory. The following classes are registered by
4164 * - {@link OO.ui.BarToolGroup BarToolGroups} (‘bar’)
4165 * - {@link OO.ui.MenuToolGroup MenuToolGroups} (‘menu’)
4166 * - {@link OO.ui.ListToolGroup ListToolGroups} (‘list’)
4168 * See {@link OO.ui.Toolbar toolbars} for an example.
4170 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4172 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4174 * @extends OO.Factory
4177 OO
.ui
.ToolGroupFactory
= function OoUiToolGroupFactory() {
4178 var i
, l
, defaultClasses
;
4179 // Parent constructor
4180 OO
.Factory
.call( this );
4182 defaultClasses
= this.constructor.static.getDefaultClasses();
4184 // Register default toolgroups
4185 for ( i
= 0, l
= defaultClasses
.length
; i
< l
; i
++ ) {
4186 this.register( defaultClasses
[ i
] );
4192 OO
.inheritClass( OO
.ui
.ToolGroupFactory
, OO
.Factory
);
4194 /* Static Methods */
4197 * Get a default set of classes to be registered on construction.
4199 * @return {Function[]} Default classes
4201 OO
.ui
.ToolGroupFactory
.static.getDefaultClasses = function () {
4204 OO
.ui
.ListToolGroup
,
4216 * @param {Object} [config] Configuration options
4218 OO
.ui
.Theme
= function OoUiTheme( config
) {
4219 // Configuration initialization
4220 config
= config
|| {};
4225 OO
.initClass( OO
.ui
.Theme
);
4230 * Get a list of classes to be applied to a widget.
4232 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
4233 * otherwise state transitions will not work properly.
4235 * @param {OO.ui.Element} element Element for which to get classes
4236 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4238 OO
.ui
.Theme
.prototype.getElementClasses = function () {
4239 return { on
: [], off
: [] };
4243 * Update CSS classes provided by the theme.
4245 * For elements with theme logic hooks, this should be called any time there's a state change.
4247 * @param {OO.ui.Element} element Element for which to update classes
4248 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4250 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
4251 var $elements
= $( [] ),
4252 classes
= this.getElementClasses( element
);
4254 if ( element
.$icon
) {
4255 $elements
= $elements
.add( element
.$icon
);
4257 if ( element
.$indicator
) {
4258 $elements
= $elements
.add( element
.$indicator
);
4262 .removeClass( classes
.off
.join( ' ' ) )
4263 .addClass( classes
.on
.join( ' ' ) );
4267 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
4268 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
4269 * order in which users will navigate through the focusable elements via the "tab" key.
4272 * // TabIndexedElement is mixed into the ButtonWidget class
4273 * // to provide a tabIndex property.
4274 * var button1 = new OO.ui.ButtonWidget( {
4278 * var button2 = new OO.ui.ButtonWidget( {
4282 * var button3 = new OO.ui.ButtonWidget( {
4286 * var button4 = new OO.ui.ButtonWidget( {
4290 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
4296 * @param {Object} [config] Configuration options
4297 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
4298 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
4299 * functionality will be applied to it instead.
4300 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
4301 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
4302 * to remove the element from the tab-navigation flow.
4304 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
4305 // Configuration initialization
4306 config
= $.extend( { tabIndex
: 0 }, config
);
4309 this.$tabIndexed
= null;
4310 this.tabIndex
= null;
4313 this.connect( this, { disable
: 'onTabIndexedElementDisable' } );
4316 this.setTabIndex( config
.tabIndex
);
4317 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
4322 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
4327 * Set the element that should use the tabindex functionality.
4329 * This method is used to retarget a tabindex mixin so that its functionality applies
4330 * to the specified element. If an element is currently using the functionality, the mixin’s
4331 * effect on that element is removed before the new element is set up.
4333 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
4336 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
4337 var tabIndex
= this.tabIndex
;
4338 // Remove attributes from old $tabIndexed
4339 this.setTabIndex( null );
4340 // Force update of new $tabIndexed
4341 this.$tabIndexed
= $tabIndexed
;
4342 this.tabIndex
= tabIndex
;
4343 return this.updateTabIndex();
4347 * Set the value of the tabindex.
4349 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
4352 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
4353 tabIndex
= typeof tabIndex
=== 'number' ? tabIndex
: null;
4355 if ( this.tabIndex
!== tabIndex
) {
4356 this.tabIndex
= tabIndex
;
4357 this.updateTabIndex();
4364 * Update the `tabindex` attribute, in case of changes to tab index or
4370 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
4371 if ( this.$tabIndexed
) {
4372 if ( this.tabIndex
!== null ) {
4373 // Do not index over disabled elements
4374 this.$tabIndexed
.attr( {
4375 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
4376 // Support: ChromeVox and NVDA
4377 // These do not seem to inherit aria-disabled from parent elements
4378 'aria-disabled': this.isDisabled().toString()
4381 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
4388 * Handle disable events.
4391 * @param {boolean} disabled Element is disabled
4393 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
4394 this.updateTabIndex();
4398 * Get the value of the tabindex.
4400 * @return {number|null} Tabindex value
4402 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
4403 return this.tabIndex
;
4407 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
4408 * interface element that can be configured with access keys for accessibility.
4409 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
4411 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
4416 * @param {Object} [config] Configuration options
4417 * @cfg {jQuery} [$button] The button element created by the class.
4418 * If this configuration is omitted, the button element will use a generated `<a>`.
4419 * @cfg {boolean} [framed=true] Render the button with a frame
4421 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
4422 // Configuration initialization
4423 config
= config
|| {};
4426 this.$button
= null;
4428 this.active
= false;
4429 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
4430 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
4431 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
4432 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
4433 this.onClickHandler
= this.onClick
.bind( this );
4434 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
4437 this.$element
.addClass( 'oo-ui-buttonElement' );
4438 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
4439 this.setButtonElement( config
.$button
|| $( '<a>' ) );
4444 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
4446 /* Static Properties */
4449 * Cancel mouse down events.
4451 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4452 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4453 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4458 * @property {boolean}
4460 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
4465 * A 'click' event is emitted when the button element is clicked.
4473 * Set the button element.
4475 * This method is used to retarget a button mixin so that its functionality applies to
4476 * the specified button element instead of the one created by the class. If a button element
4477 * is already set, the method will remove the mixin’s effect on that element.
4479 * @param {jQuery} $button Element to use as button
4481 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
4482 if ( this.$button
) {
4484 .removeClass( 'oo-ui-buttonElement-button' )
4485 .removeAttr( 'role accesskey' )
4487 mousedown
: this.onMouseDownHandler
,
4488 keydown
: this.onKeyDownHandler
,
4489 click
: this.onClickHandler
,
4490 keypress
: this.onKeyPressHandler
4494 this.$button
= $button
4495 .addClass( 'oo-ui-buttonElement-button' )
4496 .attr( { role
: 'button' } )
4498 mousedown
: this.onMouseDownHandler
,
4499 keydown
: this.onKeyDownHandler
,
4500 click
: this.onClickHandler
,
4501 keypress
: this.onKeyPressHandler
4506 * Handles mouse down events.
4509 * @param {jQuery.Event} e Mouse down event
4511 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
4512 if ( this.isDisabled() || e
.which
!== 1 ) {
4515 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4516 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4517 // reliably remove the pressed class
4518 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler
);
4519 // Prevent change of focus unless specifically configured otherwise
4520 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
4526 * Handles mouse up events.
4529 * @param {jQuery.Event} e Mouse up event
4531 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp = function ( e
) {
4532 if ( this.isDisabled() || e
.which
!== 1 ) {
4535 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4536 // Stop listening for mouseup, since we only needed this once
4537 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler
);
4541 * Handles mouse click events.
4544 * @param {jQuery.Event} e Mouse click event
4547 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
4548 if ( !this.isDisabled() && e
.which
=== 1 ) {
4549 if ( this.emit( 'click' ) ) {
4556 * Handles key down events.
4559 * @param {jQuery.Event} e Key down event
4561 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
4562 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4565 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4566 // Run the keyup handler no matter where the key is when the button is let go, so we can
4567 // reliably remove the pressed class
4568 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler
);
4572 * Handles key up events.
4575 * @param {jQuery.Event} e Key up event
4577 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyUp = function ( e
) {
4578 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4581 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4582 // Stop listening for keyup, since we only needed this once
4583 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler
);
4587 * Handles key press events.
4590 * @param {jQuery.Event} e Key press event
4593 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
4594 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
4595 if ( this.emit( 'click' ) ) {
4602 * Check if button has a frame.
4604 * @return {boolean} Button is framed
4606 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
4611 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4613 * @param {boolean} [framed] Make button framed, omit to toggle
4616 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
4617 framed
= framed
=== undefined ? !this.framed
: !!framed
;
4618 if ( framed
!== this.framed
) {
4619 this.framed
= framed
;
4621 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
4622 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
4623 this.updateThemeClasses();
4630 * Set the button's active state.
4632 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4633 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4634 * for other button types.
4636 * @param {boolean} value Make button active
4639 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
4640 this.active
= !!value
;
4641 this.$element
.toggleClass( 'oo-ui-buttonElement-active', this.active
);
4646 * Check if the button is active
4648 * @return {boolean} The button is active
4650 OO
.ui
.mixin
.ButtonElement
.prototype.isActive = function () {
4655 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4656 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4657 * items from the group is done through the interface the class provides.
4658 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4660 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4666 * @param {Object} [config] Configuration options
4667 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4668 * is omitted, the group element will use a generated `<div>`.
4670 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
4671 // Configuration initialization
4672 config
= config
|| {};
4677 this.aggregateItemEvents
= {};
4680 this.setGroupElement( config
.$group
|| $( '<div>' ) );
4686 * Set the group element.
4688 * If an element is already set, items will be moved to the new element.
4690 * @param {jQuery} $group Element to use as group
4692 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
4695 this.$group
= $group
;
4696 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4697 this.$group
.append( this.items
[ i
].$element
);
4702 * Check if a group contains no items.
4704 * @return {boolean} Group is empty
4706 OO
.ui
.mixin
.GroupElement
.prototype.isEmpty = function () {
4707 return !this.items
.length
;
4711 * Get all items in the group.
4713 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4714 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4717 * @return {OO.ui.Element[]} An array of items.
4719 OO
.ui
.mixin
.GroupElement
.prototype.getItems = function () {
4720 return this.items
.slice( 0 );
4724 * Get an item by its data.
4726 * Only the first item with matching data will be returned. To return all matching items,
4727 * use the #getItemsFromData method.
4729 * @param {Object} data Item data to search for
4730 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4732 OO
.ui
.mixin
.GroupElement
.prototype.getItemFromData = function ( data
) {
4734 hash
= OO
.getHash( data
);
4736 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4737 item
= this.items
[ i
];
4738 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4747 * Get items by their data.
4749 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4751 * @param {Object} data Item data to search for
4752 * @return {OO.ui.Element[]} Items with equivalent data
4754 OO
.ui
.mixin
.GroupElement
.prototype.getItemsFromData = function ( data
) {
4756 hash
= OO
.getHash( data
),
4759 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4760 item
= this.items
[ i
];
4761 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4770 * Aggregate the events emitted by the group.
4772 * When events are aggregated, the group will listen to all contained items for the event,
4773 * and then emit the event under a new name. The new event will contain an additional leading
4774 * parameter containing the item that emitted the original event. Other arguments emitted from
4775 * the original event are passed through.
4777 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4778 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4779 * A `null` value will remove aggregated events.
4781 * @throws {Error} An error is thrown if aggregation already exists.
4783 OO
.ui
.mixin
.GroupElement
.prototype.aggregate = function ( events
) {
4784 var i
, len
, item
, add
, remove
, itemEvent
, groupEvent
;
4786 for ( itemEvent
in events
) {
4787 groupEvent
= events
[ itemEvent
];
4789 // Remove existing aggregated event
4790 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4791 // Don't allow duplicate aggregations
4793 throw new Error( 'Duplicate item event aggregation for ' + itemEvent
);
4795 // Remove event aggregation from existing items
4796 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4797 item
= this.items
[ i
];
4798 if ( item
.connect
&& item
.disconnect
) {
4800 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4801 item
.disconnect( this, remove
);
4804 // Prevent future items from aggregating event
4805 delete this.aggregateItemEvents
[ itemEvent
];
4808 // Add new aggregate event
4810 // Make future items aggregate event
4811 this.aggregateItemEvents
[ itemEvent
] = groupEvent
;
4812 // Add event aggregation to existing items
4813 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4814 item
= this.items
[ i
];
4815 if ( item
.connect
&& item
.disconnect
) {
4817 add
[ itemEvent
] = [ 'emit', groupEvent
, item
];
4818 item
.connect( this, add
);
4826 * Add items to the group.
4828 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4829 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4831 * @param {OO.ui.Element[]} items An array of items to add to the group
4832 * @param {number} [index] Index of the insertion point
4835 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
4836 var i
, len
, item
, event
, events
, currentIndex
,
4839 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4842 // Check if item exists then remove it first, effectively "moving" it
4843 currentIndex
= this.items
.indexOf( item
);
4844 if ( currentIndex
>= 0 ) {
4845 this.removeItems( [ item
] );
4846 // Adjust index to compensate for removal
4847 if ( currentIndex
< index
) {
4852 if ( item
.connect
&& item
.disconnect
&& !$.isEmptyObject( this.aggregateItemEvents
) ) {
4854 for ( event
in this.aggregateItemEvents
) {
4855 events
[ event
] = [ 'emit', this.aggregateItemEvents
[ event
], item
];
4857 item
.connect( this, events
);
4859 item
.setElementGroup( this );
4860 itemElements
.push( item
.$element
.get( 0 ) );
4863 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
4864 this.$group
.append( itemElements
);
4865 this.items
.push
.apply( this.items
, items
);
4866 } else if ( index
=== 0 ) {
4867 this.$group
.prepend( itemElements
);
4868 this.items
.unshift
.apply( this.items
, items
);
4870 this.items
[ index
].$element
.before( itemElements
);
4871 this.items
.splice
.apply( this.items
, [ index
, 0 ].concat( items
) );
4878 * Remove the specified items from a group.
4880 * Removed items are detached (not removed) from the DOM so that they may be reused.
4881 * To remove all items from a group, you may wish to use the #clearItems method instead.
4883 * @param {OO.ui.Element[]} items An array of items to remove
4886 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
4887 var i
, len
, item
, index
, remove
, itemEvent
;
4889 // Remove specific items
4890 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4892 index
= this.items
.indexOf( item
);
4893 if ( index
!== -1 ) {
4895 item
.connect
&& item
.disconnect
&&
4896 !$.isEmptyObject( this.aggregateItemEvents
)
4899 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4900 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4902 item
.disconnect( this, remove
);
4904 item
.setElementGroup( null );
4905 this.items
.splice( index
, 1 );
4906 item
.$element
.detach();
4914 * Clear all items from the group.
4916 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4917 * To remove only a subset of items from a group, use the #removeItems method.
4921 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
4922 var i
, len
, item
, remove
, itemEvent
;
4925 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4926 item
= this.items
[ i
];
4928 item
.connect
&& item
.disconnect
&&
4929 !$.isEmptyObject( this.aggregateItemEvents
)
4932 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4933 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4935 item
.disconnect( this, remove
);
4937 item
.setElementGroup( null );
4938 item
.$element
.detach();
4946 * DraggableElement is a mixin class used to create elements that can be clicked
4947 * and dragged by a mouse to a new position within a group. This class must be used
4948 * in conjunction with OO.ui.mixin.DraggableGroupElement, which provides a container for
4949 * the draggable elements.
4956 OO
.ui
.mixin
.DraggableElement
= function OoUiMixinDraggableElement() {
4960 // Initialize and events
4962 .attr( 'draggable', true )
4963 .addClass( 'oo-ui-draggableElement' )
4965 dragstart
: this.onDragStart
.bind( this ),
4966 dragover
: this.onDragOver
.bind( this ),
4967 dragend
: this.onDragEnd
.bind( this ),
4968 drop
: this.onDrop
.bind( this )
4972 OO
.initClass( OO
.ui
.mixin
.DraggableElement
);
4979 * A dragstart event is emitted when the user clicks and begins dragging an item.
4980 * @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse.
4985 * A dragend event is emitted when the user drags an item and releases the mouse,
4986 * thus terminating the drag operation.
4991 * A drop event is emitted when the user drags an item and then releases the mouse button
4992 * over a valid target.
4995 /* Static Properties */
4998 * @inheritdoc OO.ui.mixin.ButtonElement
5000 OO
.ui
.mixin
.DraggableElement
.static.cancelButtonMouseDownEvents
= false;
5005 * Respond to dragstart event.
5008 * @param {jQuery.Event} event jQuery event
5011 OO
.ui
.mixin
.DraggableElement
.prototype.onDragStart = function ( e
) {
5012 var dataTransfer
= e
.originalEvent
.dataTransfer
;
5013 // Define drop effect
5014 dataTransfer
.dropEffect
= 'none';
5015 dataTransfer
.effectAllowed
= 'move';
5017 // We must set up a dataTransfer data property or Firefox seems to
5018 // ignore the fact the element is draggable.
5020 dataTransfer
.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
5022 // The above is only for Firefox. Move on if it fails.
5024 // Add dragging class
5025 this.$element
.addClass( 'oo-ui-draggableElement-dragging' );
5027 this.emit( 'dragstart', this );
5032 * Respond to dragend event.
5037 OO
.ui
.mixin
.DraggableElement
.prototype.onDragEnd = function () {
5038 this.$element
.removeClass( 'oo-ui-draggableElement-dragging' );
5039 this.emit( 'dragend' );
5043 * Handle drop event.
5046 * @param {jQuery.Event} event jQuery event
5049 OO
.ui
.mixin
.DraggableElement
.prototype.onDrop = function ( e
) {
5051 this.emit( 'drop', e
);
5055 * In order for drag/drop to work, the dragover event must
5056 * return false and stop propogation.
5060 OO
.ui
.mixin
.DraggableElement
.prototype.onDragOver = function ( e
) {
5066 * Store it in the DOM so we can access from the widget drag event
5069 * @param {number} Item index
5071 OO
.ui
.mixin
.DraggableElement
.prototype.setIndex = function ( index
) {
5072 if ( this.index
!== index
) {
5074 this.$element
.data( 'index', index
);
5082 * @return {number} Item index
5084 OO
.ui
.mixin
.DraggableElement
.prototype.getIndex = function () {
5089 * DraggableGroupElement is a mixin class used to create a group element to
5090 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
5091 * The class is used with OO.ui.mixin.DraggableElement.
5095 * @mixins OO.ui.mixin.GroupElement
5098 * @param {Object} [config] Configuration options
5099 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
5100 * should match the layout of the items. Items displayed in a single row
5101 * or in several rows should use horizontal orientation. The vertical orientation should only be
5102 * used when the items are displayed in a single column. Defaults to 'vertical'
5104 OO
.ui
.mixin
.DraggableGroupElement
= function OoUiMixinDraggableGroupElement( config
) {
5105 // Configuration initialization
5106 config
= config
|| {};
5108 // Parent constructor
5109 OO
.ui
.mixin
.GroupElement
.call( this, config
);
5112 this.orientation
= config
.orientation
|| 'vertical';
5113 this.dragItem
= null;
5114 this.itemDragOver
= null;
5116 this.sideInsertion
= '';
5120 dragstart
: 'itemDragStart',
5121 dragend
: 'itemDragEnd',
5124 this.connect( this, {
5125 itemDragStart
: 'onItemDragStart',
5126 itemDrop
: 'onItemDrop',
5127 itemDragEnd
: 'onItemDragEnd'
5130 dragover
: this.onDragOver
.bind( this ),
5131 dragleave
: this.onDragLeave
.bind( this )
5135 if ( Array
.isArray( config
.items
) ) {
5136 this.addItems( config
.items
);
5138 this.$placeholder
= $( '<div>' )
5139 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
5141 .addClass( 'oo-ui-draggableGroupElement' )
5142 .append( this.$status
)
5143 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation
=== 'horizontal' )
5144 .prepend( this.$placeholder
);
5148 OO
.mixinClass( OO
.ui
.mixin
.DraggableGroupElement
, OO
.ui
.mixin
.GroupElement
);
5153 * A 'reorder' event is emitted when the order of items in the group changes.
5156 * @param {OO.ui.mixin.DraggableElement} item Reordered item
5157 * @param {number} [newIndex] New index for the item
5163 * Respond to item drag start event
5166 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5168 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDragStart = function ( item
) {
5171 // Map the index of each object
5172 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5173 this.items
[ i
].setIndex( i
);
5176 if ( this.orientation
=== 'horizontal' ) {
5177 // Set the height of the indicator
5178 this.$placeholder
.css( {
5179 height
: item
.$element
.outerHeight(),
5183 // Set the width of the indicator
5184 this.$placeholder
.css( {
5186 width
: item
.$element
.outerWidth()
5189 this.setDragItem( item
);
5193 * Respond to item drag end event
5197 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDragEnd = function () {
5198 this.unsetDragItem();
5203 * Handle drop event and switch the order of the items accordingly
5206 * @param {OO.ui.mixin.DraggableElement} item Dropped item
5209 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDrop = function ( item
) {
5210 var toIndex
= item
.getIndex();
5211 // Check if the dropped item is from the current group
5212 // TODO: Figure out a way to configure a list of legally droppable
5213 // elements even if they are not yet in the list
5214 if ( this.getDragItem() ) {
5215 // If the insertion point is 'after', the insertion index
5216 // is shifted to the right (or to the left in RTL, hence 'after')
5217 if ( this.sideInsertion
=== 'after' ) {
5220 // Emit change event
5221 this.emit( 'reorder', this.getDragItem(), toIndex
);
5223 this.unsetDragItem();
5224 // Return false to prevent propogation
5229 * Handle dragleave event.
5233 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onDragLeave = function () {
5234 // This means the item was dragged outside the widget
5237 .addClass( 'oo-ui-element-hidden' );
5241 * Respond to dragover event
5244 * @param {jQuery.Event} event Event details
5246 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onDragOver = function ( e
) {
5247 var dragOverObj
, $optionWidget
, itemOffset
, itemMidpoint
, itemBoundingRect
,
5248 itemSize
, cssOutput
, dragPosition
, itemIndex
, itemPosition
,
5249 clientX
= e
.originalEvent
.clientX
,
5250 clientY
= e
.originalEvent
.clientY
;
5252 // Get the OptionWidget item we are dragging over
5253 dragOverObj
= this.getElementDocument().elementFromPoint( clientX
, clientY
);
5254 $optionWidget
= $( dragOverObj
).closest( '.oo-ui-draggableElement' );
5255 if ( $optionWidget
[ 0 ] ) {
5256 itemOffset
= $optionWidget
.offset();
5257 itemBoundingRect
= $optionWidget
[ 0 ].getBoundingClientRect();
5258 itemPosition
= $optionWidget
.position();
5259 itemIndex
= $optionWidget
.data( 'index' );
5264 this.isDragging() &&
5265 itemIndex
!== this.getDragItem().getIndex()
5267 if ( this.orientation
=== 'horizontal' ) {
5268 // Calculate where the mouse is relative to the item width
5269 itemSize
= itemBoundingRect
.width
;
5270 itemMidpoint
= itemBoundingRect
.left
+ itemSize
/ 2;
5271 dragPosition
= clientX
;
5272 // Which side of the item we hover over will dictate
5273 // where the placeholder will appear, on the left or
5276 left
: dragPosition
< itemMidpoint
? itemPosition
.left
: itemPosition
.left
+ itemSize
,
5277 top
: itemPosition
.top
5280 // Calculate where the mouse is relative to the item height
5281 itemSize
= itemBoundingRect
.height
;
5282 itemMidpoint
= itemBoundingRect
.top
+ itemSize
/ 2;
5283 dragPosition
= clientY
;
5284 // Which side of the item we hover over will dictate
5285 // where the placeholder will appear, on the top or
5288 top
: dragPosition
< itemMidpoint
? itemPosition
.top
: itemPosition
.top
+ itemSize
,
5289 left
: itemPosition
.left
5292 // Store whether we are before or after an item to rearrange
5293 // For horizontal layout, we need to account for RTL, as this is flipped
5294 if ( this.orientation
=== 'horizontal' && this.$element
.css( 'direction' ) === 'rtl' ) {
5295 this.sideInsertion
= dragPosition
< itemMidpoint
? 'after' : 'before';
5297 this.sideInsertion
= dragPosition
< itemMidpoint
? 'before' : 'after';
5299 // Add drop indicator between objects
5302 .removeClass( 'oo-ui-element-hidden' );
5304 // This means the item was dragged outside the widget
5307 .addClass( 'oo-ui-element-hidden' );
5314 * Set a dragged item
5316 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5318 OO
.ui
.mixin
.DraggableGroupElement
.prototype.setDragItem = function ( item
) {
5319 this.dragItem
= item
;
5323 * Unset the current dragged item
5325 OO
.ui
.mixin
.DraggableGroupElement
.prototype.unsetDragItem = function () {
5326 this.dragItem
= null;
5327 this.itemDragOver
= null;
5328 this.$placeholder
.addClass( 'oo-ui-element-hidden' );
5329 this.sideInsertion
= '';
5333 * Get the item that is currently being dragged.
5335 * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
5337 OO
.ui
.mixin
.DraggableGroupElement
.prototype.getDragItem = function () {
5338 return this.dragItem
;
5342 * Check if an item in the group is currently being dragged.
5344 * @return {Boolean} Item is being dragged
5346 OO
.ui
.mixin
.DraggableGroupElement
.prototype.isDragging = function () {
5347 return this.getDragItem() !== null;
5351 * IconElement is often mixed into other classes to generate an icon.
5352 * Icons are graphics, about the size of normal text. They are used to aid the user
5353 * in locating a control or to convey information in a space-efficient way. See the
5354 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
5355 * included in the library.
5357 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5363 * @param {Object} [config] Configuration options
5364 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
5365 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
5366 * the icon element be set to an existing icon instead of the one generated by this class, set a
5367 * value using a jQuery selection. For example:
5369 * // Use a <div> tag instead of a <span>
5371 * // Use an existing icon element instead of the one generated by the class
5372 * $icon: this.$element
5373 * // Use an icon element from a child widget
5374 * $icon: this.childwidget.$element
5375 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
5376 * symbolic names. A map is used for i18n purposes and contains a `default` icon
5377 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
5378 * by the user's language.
5380 * Example of an i18n map:
5382 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5383 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
5384 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5385 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
5386 * text. The icon title is displayed when users move the mouse over the icon.
5388 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
5389 // Configuration initialization
5390 config
= config
|| {};
5395 this.iconTitle
= null;
5398 this.setIcon( config
.icon
|| this.constructor.static.icon
);
5399 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
5400 this.setIconElement( config
.$icon
|| $( '<span>' ) );
5405 OO
.initClass( OO
.ui
.mixin
.IconElement
);
5407 /* Static Properties */
5410 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
5411 * for i18n purposes and contains a `default` icon name and additional names keyed by
5412 * language code. The `default` name is used when no icon is keyed by the user's language.
5414 * Example of an i18n map:
5416 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5418 * Note: the static property will be overridden if the #icon configuration is used.
5422 * @property {Object|string}
5424 OO
.ui
.mixin
.IconElement
.static.icon
= null;
5427 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5428 * function that returns title text, or `null` for no title.
5430 * The static property will be overridden if the #iconTitle configuration is used.
5434 * @property {string|Function|null}
5436 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
5441 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5442 * applies to the specified icon element instead of the one created by the class. If an icon
5443 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5444 * and mixin methods will no longer affect the element.
5446 * @param {jQuery} $icon Element to use as icon
5448 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
5451 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
5452 .removeAttr( 'title' );
5456 .addClass( 'oo-ui-iconElement-icon' )
5457 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
5458 if ( this.iconTitle
!== null ) {
5459 this.$icon
.attr( 'title', this.iconTitle
);
5462 this.updateThemeClasses();
5466 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5467 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5470 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5471 * by language code, or `null` to remove the icon.
5474 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
5475 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
5476 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
5478 if ( this.icon
!== icon
) {
5480 if ( this.icon
!== null ) {
5481 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
5483 if ( icon
!== null ) {
5484 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
5490 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
5491 this.updateThemeClasses();
5497 * Set the icon title. Use `null` to remove the title.
5499 * @param {string|Function|null} iconTitle A text string used as the icon title,
5500 * a function that returns title text, or `null` for no title.
5503 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
5504 iconTitle
= typeof iconTitle
=== 'function' ||
5505 ( typeof iconTitle
=== 'string' && iconTitle
.length
) ?
5506 OO
.ui
.resolveMsg( iconTitle
) : null;
5508 if ( this.iconTitle
!== iconTitle
) {
5509 this.iconTitle
= iconTitle
;
5511 if ( this.iconTitle
!== null ) {
5512 this.$icon
.attr( 'title', iconTitle
);
5514 this.$icon
.removeAttr( 'title' );
5523 * Get the symbolic name of the icon.
5525 * @return {string} Icon name
5527 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
5532 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5534 * @return {string} Icon title text
5536 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
5537 return this.iconTitle
;
5541 * IndicatorElement is often mixed into other classes to generate an indicator.
5542 * Indicators are small graphics that are generally used in two ways:
5544 * - To draw attention to the status of an item. For example, an indicator might be
5545 * used to show that an item in a list has errors that need to be resolved.
5546 * - To clarify the function of a control that acts in an exceptional way (a button
5547 * that opens a menu instead of performing an action directly, for example).
5549 * For a list of indicators included in the library, please see the
5550 * [OOjs UI documentation on MediaWiki] [1].
5552 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5558 * @param {Object} [config] Configuration options
5559 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5560 * configuration is omitted, the indicator element will use a generated `<span>`.
5561 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5562 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5564 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5565 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5566 * or a function that returns title text. The indicator title is displayed when users move
5567 * the mouse over the indicator.
5569 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
5570 // Configuration initialization
5571 config
= config
|| {};
5574 this.$indicator
= null;
5575 this.indicator
= null;
5576 this.indicatorTitle
= null;
5579 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
5580 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
5581 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
5586 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
5588 /* Static Properties */
5591 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5592 * The static property will be overridden if the #indicator configuration is used.
5596 * @property {string|null}
5598 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
5601 * A text string used as the indicator title, a function that returns title text, or `null`
5602 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5606 * @property {string|Function|null}
5608 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
5613 * Set the indicator element.
5615 * If an element is already set, it will be cleaned up before setting up the new element.
5617 * @param {jQuery} $indicator Element to use as indicator
5619 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
5620 if ( this.$indicator
) {
5622 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
5623 .removeAttr( 'title' );
5626 this.$indicator
= $indicator
5627 .addClass( 'oo-ui-indicatorElement-indicator' )
5628 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
5629 if ( this.indicatorTitle
!== null ) {
5630 this.$indicator
.attr( 'title', this.indicatorTitle
);
5633 this.updateThemeClasses();
5637 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5639 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5642 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
5643 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
5645 if ( this.indicator
!== indicator
) {
5646 if ( this.$indicator
) {
5647 if ( this.indicator
!== null ) {
5648 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
5650 if ( indicator
!== null ) {
5651 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
5654 this.indicator
= indicator
;
5657 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
5658 this.updateThemeClasses();
5664 * Set the indicator title.
5666 * The title is displayed when a user moves the mouse over the indicator.
5668 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5669 * `null` for no indicator title
5672 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
5673 indicatorTitle
= typeof indicatorTitle
=== 'function' ||
5674 ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ?
5675 OO
.ui
.resolveMsg( indicatorTitle
) : null;
5677 if ( this.indicatorTitle
!== indicatorTitle
) {
5678 this.indicatorTitle
= indicatorTitle
;
5679 if ( this.$indicator
) {
5680 if ( this.indicatorTitle
!== null ) {
5681 this.$indicator
.attr( 'title', indicatorTitle
);
5683 this.$indicator
.removeAttr( 'title' );
5692 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5694 * @return {string} Symbolic name of indicator
5696 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
5697 return this.indicator
;
5701 * Get the indicator title.
5703 * The title is displayed when a user moves the mouse over the indicator.
5705 * @return {string} Indicator title text
5707 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
5708 return this.indicatorTitle
;
5712 * LabelElement is often mixed into other classes to generate a label, which
5713 * helps identify the function of an interface element.
5714 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5716 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5722 * @param {Object} [config] Configuration options
5723 * @cfg {jQuery} [$label] The label element created by the class. If this
5724 * configuration is omitted, the label element will use a generated `<span>`.
5725 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
5726 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
5727 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
5728 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5729 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5730 * The label will be truncated to fit if necessary.
5732 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
5733 // Configuration initialization
5734 config
= config
|| {};
5739 this.autoFitLabel
= config
.autoFitLabel
=== undefined || !!config
.autoFitLabel
;
5742 this.setLabel( config
.label
|| this.constructor.static.label
);
5743 this.setLabelElement( config
.$label
|| $( '<span>' ) );
5748 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
5753 * @event labelChange
5754 * @param {string} value
5757 /* Static Properties */
5760 * The label text. The label can be specified as a plaintext string, a function that will
5761 * produce a string in the future, or `null` for no label. The static value will
5762 * be overridden if a label is specified with the #label config option.
5766 * @property {string|Function|null}
5768 OO
.ui
.mixin
.LabelElement
.static.label
= null;
5773 * Set the label element.
5775 * If an element is already set, it will be cleaned up before setting up the new element.
5777 * @param {jQuery} $label Element to use as label
5779 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
5780 if ( this.$label
) {
5781 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
5784 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
5785 this.setLabelContent( this.label
);
5791 * An empty string will result in the label being hidden. A string containing only whitespace will
5792 * be converted to a single ` `.
5794 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5795 * text; or null for no label
5798 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
5799 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
5800 label
= ( ( typeof label
=== 'string' && label
.length
) || label
instanceof jQuery
|| label
instanceof OO
.ui
.HtmlSnippet
) ? label
: null;
5802 this.$element
.toggleClass( 'oo-ui-labelElement', !!label
);
5804 if ( this.label
!== label
) {
5805 if ( this.$label
) {
5806 this.setLabelContent( label
);
5809 this.emit( 'labelChange' );
5818 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5819 * text; or null for no label
5821 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
5830 OO
.ui
.mixin
.LabelElement
.prototype.fitLabel = function () {
5831 if ( this.$label
&& this.$label
.autoEllipsis
&& this.autoFitLabel
) {
5832 this.$label
.autoEllipsis( { hasSpan
: false, tooltip
: true } );
5839 * Set the content of the label.
5841 * Do not call this method until after the label element has been set by #setLabelElement.
5844 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5845 * text; or null for no label
5847 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
5848 if ( typeof label
=== 'string' ) {
5849 if ( label
.match( /^\s*$/ ) ) {
5850 // Convert whitespace only string to a single non-breaking space
5851 this.$label
.html( ' ' );
5853 this.$label
.text( label
);
5855 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
5856 this.$label
.html( label
.toString() );
5857 } else if ( label
instanceof jQuery
) {
5858 this.$label
.empty().append( label
);
5860 this.$label
.empty();
5865 * LookupElement is a mixin that creates a {@link OO.ui.FloatingMenuSelectWidget menu} of suggested values for
5866 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
5867 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
5868 * from the lookup menu, that value becomes the value of the input field.
5870 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
5871 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
5872 * re-enable lookups.
5874 * See the [OOjs UI demos][1] for an example.
5876 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
5882 * @param {Object} [config] Configuration options
5883 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
5884 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
5885 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
5886 * By default, the lookup menu is not generated and displayed until the user begins to type.
5888 OO
.ui
.mixin
.LookupElement
= function OoUiMixinLookupElement( config
) {
5889 // Configuration initialization
5890 config
= config
|| {};
5893 this.$overlay
= config
.$overlay
|| this.$element
;
5894 this.lookupMenu
= new OO
.ui
.FloatingMenuSelectWidget( {
5897 $container
: config
.$container
|| this.$element
5900 this.allowSuggestionsWhenEmpty
= config
.allowSuggestionsWhenEmpty
|| false;
5902 this.lookupCache
= {};
5903 this.lookupQuery
= null;
5904 this.lookupRequest
= null;
5905 this.lookupsDisabled
= false;
5906 this.lookupInputFocused
= false;
5910 focus
: this.onLookupInputFocus
.bind( this ),
5911 blur
: this.onLookupInputBlur
.bind( this ),
5912 mousedown
: this.onLookupInputMouseDown
.bind( this )
5914 this.connect( this, { change
: 'onLookupInputChange' } );
5915 this.lookupMenu
.connect( this, {
5916 toggle
: 'onLookupMenuToggle',
5917 choose
: 'onLookupMenuItemChoose'
5921 this.$element
.addClass( 'oo-ui-lookupElement' );
5922 this.lookupMenu
.$element
.addClass( 'oo-ui-lookupElement-menu' );
5923 this.$overlay
.append( this.lookupMenu
.$element
);
5929 * Handle input focus event.
5932 * @param {jQuery.Event} e Input focus event
5934 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputFocus = function () {
5935 this.lookupInputFocused
= true;
5936 this.populateLookupMenu();
5940 * Handle input blur event.
5943 * @param {jQuery.Event} e Input blur event
5945 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputBlur = function () {
5946 this.closeLookupMenu();
5947 this.lookupInputFocused
= false;
5951 * Handle input mouse down event.
5954 * @param {jQuery.Event} e Input mouse down event
5956 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputMouseDown = function () {
5957 // Only open the menu if the input was already focused.
5958 // This way we allow the user to open the menu again after closing it with Esc
5959 // by clicking in the input. Opening (and populating) the menu when initially
5960 // clicking into the input is handled by the focus handler.
5961 if ( this.lookupInputFocused
&& !this.lookupMenu
.isVisible() ) {
5962 this.populateLookupMenu();
5967 * Handle input change event.
5970 * @param {string} value New input value
5972 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputChange = function () {
5973 if ( this.lookupInputFocused
) {
5974 this.populateLookupMenu();
5979 * Handle the lookup menu being shown/hidden.
5982 * @param {boolean} visible Whether the lookup menu is now visible.
5984 OO
.ui
.mixin
.LookupElement
.prototype.onLookupMenuToggle = function ( visible
) {
5986 // When the menu is hidden, abort any active request and clear the menu.
5987 // This has to be done here in addition to closeLookupMenu(), because
5988 // MenuSelectWidget will close itself when the user presses Esc.
5989 this.abortLookupRequest();
5990 this.lookupMenu
.clearItems();
5995 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5998 * @param {OO.ui.MenuOptionWidget} item Selected item
6000 OO
.ui
.mixin
.LookupElement
.prototype.onLookupMenuItemChoose = function ( item
) {
6001 this.setValue( item
.getData() );
6008 * @return {OO.ui.FloatingMenuSelectWidget}
6010 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenu = function () {
6011 return this.lookupMenu
;
6015 * Disable or re-enable lookups.
6017 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
6019 * @param {boolean} disabled Disable lookups
6021 OO
.ui
.mixin
.LookupElement
.prototype.setLookupsDisabled = function ( disabled
) {
6022 this.lookupsDisabled
= !!disabled
;
6026 * Open the menu. If there are no entries in the menu, this does nothing.
6031 OO
.ui
.mixin
.LookupElement
.prototype.openLookupMenu = function () {
6032 if ( !this.lookupMenu
.isEmpty() ) {
6033 this.lookupMenu
.toggle( true );
6039 * Close the menu, empty it, and abort any pending request.
6044 OO
.ui
.mixin
.LookupElement
.prototype.closeLookupMenu = function () {
6045 this.lookupMenu
.toggle( false );
6046 this.abortLookupRequest();
6047 this.lookupMenu
.clearItems();
6052 * Request menu items based on the input's current value, and when they arrive,
6053 * populate the menu with these items and show the menu.
6055 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
6060 OO
.ui
.mixin
.LookupElement
.prototype.populateLookupMenu = function () {
6062 value
= this.getValue();
6064 if ( this.lookupsDisabled
|| this.isReadOnly() ) {
6068 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
6069 if ( !this.allowSuggestionsWhenEmpty
&& value
=== '' ) {
6070 this.closeLookupMenu();
6071 // Skip population if there is already a request pending for the current value
6072 } else if ( value
!== this.lookupQuery
) {
6073 this.getLookupMenuItems()
6074 .done( function ( items
) {
6075 widget
.lookupMenu
.clearItems();
6076 if ( items
.length
) {
6080 widget
.initializeLookupMenuSelection();
6082 widget
.lookupMenu
.toggle( false );
6085 .fail( function () {
6086 widget
.lookupMenu
.clearItems();
6094 * Highlight the first selectable item in the menu.
6099 OO
.ui
.mixin
.LookupElement
.prototype.initializeLookupMenuSelection = function () {
6100 if ( !this.lookupMenu
.getSelectedItem() ) {
6101 this.lookupMenu
.highlightItem( this.lookupMenu
.getFirstSelectableItem() );
6106 * Get lookup menu items for the current query.
6109 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
6110 * the done event. If the request was aborted to make way for a subsequent request, this promise
6111 * will not be rejected: it will remain pending forever.
6113 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenuItems = function () {
6115 value
= this.getValue(),
6116 deferred
= $.Deferred(),
6119 this.abortLookupRequest();
6120 if ( Object
.prototype.hasOwnProperty
.call( this.lookupCache
, value
) ) {
6121 deferred
.resolve( this.getLookupMenuOptionsFromData( this.lookupCache
[ value
] ) );
6124 this.lookupQuery
= value
;
6125 ourRequest
= this.lookupRequest
= this.getLookupRequest();
6127 .always( function () {
6128 // We need to pop pending even if this is an old request, otherwise
6129 // the widget will remain pending forever.
6130 // TODO: this assumes that an aborted request will fail or succeed soon after
6131 // being aborted, or at least eventually. It would be nice if we could popPending()
6132 // at abort time, but only if we knew that we hadn't already called popPending()
6133 // for that request.
6134 widget
.popPending();
6136 .done( function ( response
) {
6137 // If this is an old request (and aborting it somehow caused it to still succeed),
6138 // ignore its success completely
6139 if ( ourRequest
=== widget
.lookupRequest
) {
6140 widget
.lookupQuery
= null;
6141 widget
.lookupRequest
= null;
6142 widget
.lookupCache
[ value
] = widget
.getLookupCacheDataFromResponse( response
);
6143 deferred
.resolve( widget
.getLookupMenuOptionsFromData( widget
.lookupCache
[ value
] ) );
6146 .fail( function () {
6147 // If this is an old request (or a request failing because it's being aborted),
6148 // ignore its failure completely
6149 if ( ourRequest
=== widget
.lookupRequest
) {
6150 widget
.lookupQuery
= null;
6151 widget
.lookupRequest
= null;
6156 return deferred
.promise();
6160 * Abort the currently pending lookup request, if any.
6164 OO
.ui
.mixin
.LookupElement
.prototype.abortLookupRequest = function () {
6165 var oldRequest
= this.lookupRequest
;
6167 // First unset this.lookupRequest to the fail handler will notice
6168 // that the request is no longer current
6169 this.lookupRequest
= null;
6170 this.lookupQuery
= null;
6176 * Get a new request object of the current lookup query value.
6180 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
6182 OO
.ui
.mixin
.LookupElement
.prototype.getLookupRequest = function () {
6183 // Stub, implemented in subclass
6188 * Pre-process data returned by the request from #getLookupRequest.
6190 * The return value of this function will be cached, and any further queries for the given value
6191 * will use the cache rather than doing API requests.
6195 * @param {Mixed} response Response from server
6196 * @return {Mixed} Cached result data
6198 OO
.ui
.mixin
.LookupElement
.prototype.getLookupCacheDataFromResponse = function () {
6199 // Stub, implemented in subclass
6204 * Get a list of menu option widgets from the (possibly cached) data returned by
6205 * #getLookupCacheDataFromResponse.
6209 * @param {Mixed} data Cached result data, usually an array
6210 * @return {OO.ui.MenuOptionWidget[]} Menu items
6212 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenuOptionsFromData = function () {
6213 // Stub, implemented in subclass
6218 * Set the read-only state of the widget.
6220 * This will also disable/enable the lookups functionality.
6222 * @param {boolean} readOnly Make input read-only
6225 OO
.ui
.mixin
.LookupElement
.prototype.setReadOnly = function ( readOnly
) {
6227 // Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget
6228 OO
.ui
.TextInputWidget
.prototype.setReadOnly
.call( this, readOnly
);
6230 // During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor
6231 if ( this.isReadOnly() && this.lookupMenu
) {
6232 this.closeLookupMenu();
6239 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
6240 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
6241 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
6242 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
6248 * @param {Object} [config] Configuration options
6249 * @cfg {Object} [popup] Configuration to pass to popup
6250 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
6252 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
6253 // Configuration initialization
6254 config
= config
|| {};
6257 this.popup
= new OO
.ui
.PopupWidget( $.extend(
6258 { autoClose
: true },
6260 { $autoCloseIgnore
: this.$element
}
6269 * @return {OO.ui.PopupWidget} Popup widget
6271 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
6276 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
6277 * additional functionality to an element created by another class. The class provides
6278 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
6279 * which are used to customize the look and feel of a widget to better describe its
6280 * importance and functionality.
6282 * The library currently contains the following styling flags for general use:
6284 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
6285 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
6286 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
6288 * The flags affect the appearance of the buttons:
6291 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
6292 * var button1 = new OO.ui.ButtonWidget( {
6293 * label: 'Constructive',
6294 * flags: 'constructive'
6296 * var button2 = new OO.ui.ButtonWidget( {
6297 * label: 'Destructive',
6298 * flags: 'destructive'
6300 * var button3 = new OO.ui.ButtonWidget( {
6301 * label: 'Progressive',
6302 * flags: 'progressive'
6304 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
6306 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
6307 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6309 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6315 * @param {Object} [config] Configuration options
6316 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
6317 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
6318 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6319 * @cfg {jQuery} [$flagged] The flagged element. By default,
6320 * the flagged functionality is applied to the element created by the class ($element).
6321 * If a different element is specified, the flagged functionality will be applied to it instead.
6323 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
6324 // Configuration initialization
6325 config
= config
|| {};
6329 this.$flagged
= null;
6332 this.setFlags( config
.flags
);
6333 this.setFlaggedElement( config
.$flagged
|| this.$element
);
6340 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
6341 * parameter contains the name of each modified flag and indicates whether it was
6344 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
6345 * that the flag was added, `false` that the flag was removed.
6351 * Set the flagged element.
6353 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
6354 * If an element is already set, the method will remove the mixin’s effect on that element.
6356 * @param {jQuery} $flagged Element that should be flagged
6358 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
6359 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
6360 return 'oo-ui-flaggedElement-' + flag
;
6363 if ( this.$flagged
) {
6364 this.$flagged
.removeClass( classNames
);
6367 this.$flagged
= $flagged
.addClass( classNames
);
6371 * Check if the specified flag is set.
6373 * @param {string} flag Name of flag
6374 * @return {boolean} The flag is set
6376 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
6377 // This may be called before the constructor, thus before this.flags is set
6378 return this.flags
&& ( flag
in this.flags
);
6382 * Get the names of all flags set.
6384 * @return {string[]} Flag names
6386 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
6387 // This may be called before the constructor, thus before this.flags is set
6388 return Object
.keys( this.flags
|| {} );
6397 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
6398 var flag
, className
,
6401 classPrefix
= 'oo-ui-flaggedElement-';
6403 for ( flag
in this.flags
) {
6404 className
= classPrefix
+ flag
;
6405 changes
[ flag
] = false;
6406 delete this.flags
[ flag
];
6407 remove
.push( className
);
6410 if ( this.$flagged
) {
6411 this.$flagged
.removeClass( remove
.join( ' ' ) );
6414 this.updateThemeClasses();
6415 this.emit( 'flag', changes
);
6421 * Add one or more flags.
6423 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
6424 * or an object keyed by flag name with a boolean value that indicates whether the flag should
6425 * be added (`true`) or removed (`false`).
6429 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
6430 var i
, len
, flag
, className
,
6434 classPrefix
= 'oo-ui-flaggedElement-';
6436 if ( typeof flags
=== 'string' ) {
6437 className
= classPrefix
+ flags
;
6439 if ( !this.flags
[ flags
] ) {
6440 this.flags
[ flags
] = true;
6441 add
.push( className
);
6443 } else if ( Array
.isArray( flags
) ) {
6444 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
6446 className
= classPrefix
+ flag
;
6448 if ( !this.flags
[ flag
] ) {
6449 changes
[ flag
] = true;
6450 this.flags
[ flag
] = true;
6451 add
.push( className
);
6454 } else if ( OO
.isPlainObject( flags
) ) {
6455 for ( flag
in flags
) {
6456 className
= classPrefix
+ flag
;
6457 if ( flags
[ flag
] ) {
6459 if ( !this.flags
[ flag
] ) {
6460 changes
[ flag
] = true;
6461 this.flags
[ flag
] = true;
6462 add
.push( className
);
6466 if ( this.flags
[ flag
] ) {
6467 changes
[ flag
] = false;
6468 delete this.flags
[ flag
];
6469 remove
.push( className
);
6475 if ( this.$flagged
) {
6477 .addClass( add
.join( ' ' ) )
6478 .removeClass( remove
.join( ' ' ) );
6481 this.updateThemeClasses();
6482 this.emit( 'flag', changes
);
6488 * TitledElement is mixed into other classes to provide a `title` attribute.
6489 * Titles are rendered by the browser and are made visible when the user moves
6490 * the mouse over the element. Titles are not visible on touch devices.
6493 * // TitledElement provides a 'title' attribute to the
6494 * // ButtonWidget class
6495 * var button = new OO.ui.ButtonWidget( {
6496 * label: 'Button with Title',
6497 * title: 'I am a button'
6499 * $( 'body' ).append( button.$element );
6505 * @param {Object} [config] Configuration options
6506 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6507 * If this config is omitted, the title functionality is applied to $element, the
6508 * element created by the class.
6509 * @cfg {string|Function} [title] The title text or a function that returns text. If
6510 * this config is omitted, the value of the {@link #static-title static title} property is used.
6512 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
6513 // Configuration initialization
6514 config
= config
|| {};
6517 this.$titled
= null;
6521 this.setTitle( config
.title
|| this.constructor.static.title
);
6522 this.setTitledElement( config
.$titled
|| this.$element
);
6527 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
6529 /* Static Properties */
6532 * The title text, a function that returns text, or `null` for no title. The value of the static property
6533 * is overridden if the #title config option is used.
6537 * @property {string|Function|null}
6539 OO
.ui
.mixin
.TitledElement
.static.title
= null;
6544 * Set the titled element.
6546 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6547 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6549 * @param {jQuery} $titled Element that should use the 'titled' functionality
6551 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
6552 if ( this.$titled
) {
6553 this.$titled
.removeAttr( 'title' );
6556 this.$titled
= $titled
;
6558 this.$titled
.attr( 'title', this.title
);
6565 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6568 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
6569 title
= typeof title
=== 'string' ? OO
.ui
.resolveMsg( title
) : null;
6571 if ( this.title
!== title
) {
6572 if ( this.$titled
) {
6573 if ( title
!== null ) {
6574 this.$titled
.attr( 'title', title
);
6576 this.$titled
.removeAttr( 'title' );
6588 * @return {string} Title string
6590 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
6595 * Element that can be automatically clipped to visible boundaries.
6597 * Whenever the element's natural height changes, you have to call
6598 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
6599 * clipping correctly.
6601 * The dimensions of #$clippableContainer will be compared to the boundaries of the
6602 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
6603 * then #$clippable will be given a fixed reduced height and/or width and will be made
6604 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
6605 * but you can build a static footer by setting #$clippableContainer to an element that contains
6606 * #$clippable and the footer.
6612 * @param {Object} [config] Configuration options
6613 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
6614 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
6615 * omit to use #$clippable
6617 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
6618 // Configuration initialization
6619 config
= config
|| {};
6622 this.$clippable
= null;
6623 this.$clippableContainer
= null;
6624 this.clipping
= false;
6625 this.clippedHorizontally
= false;
6626 this.clippedVertically
= false;
6627 this.$clippableScrollableContainer
= null;
6628 this.$clippableScroller
= null;
6629 this.$clippableWindow
= null;
6630 this.idealWidth
= null;
6631 this.idealHeight
= null;
6632 this.onClippableScrollHandler
= this.clip
.bind( this );
6633 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
6636 if ( config
.$clippableContainer
) {
6637 this.setClippableContainer( config
.$clippableContainer
);
6639 this.setClippableElement( config
.$clippable
|| this.$element
);
6645 * Set clippable element.
6647 * If an element is already set, it will be cleaned up before setting up the new element.
6649 * @param {jQuery} $clippable Element to make clippable
6651 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
6652 if ( this.$clippable
) {
6653 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
6654 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6655 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6658 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
6663 * Set clippable container.
6665 * This is the container that will be measured when deciding whether to clip. When clipping,
6666 * #$clippable will be resized in order to keep the clippable container fully visible.
6668 * If the clippable container is unset, #$clippable will be used.
6670 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
6672 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableContainer = function ( $clippableContainer
) {
6673 this.$clippableContainer
= $clippableContainer
;
6674 if ( this.$clippable
) {
6682 * Do not turn clipping on until after the element is attached to the DOM and visible.
6684 * @param {boolean} [clipping] Enable clipping, omit to toggle
6687 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
6688 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
6690 if ( this.clipping
!== clipping
) {
6691 this.clipping
= clipping
;
6693 this.$clippableScrollableContainer
= $( this.getClosestScrollableElementContainer() );
6694 // If the clippable container is the root, we have to listen to scroll events and check
6695 // jQuery.scrollTop on the window because of browser inconsistencies
6696 this.$clippableScroller
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
6697 $( OO
.ui
.Element
.static.getWindow( this.$clippableScrollableContainer
) ) :
6698 this.$clippableScrollableContainer
;
6699 this.$clippableScroller
.on( 'scroll', this.onClippableScrollHandler
);
6700 this.$clippableWindow
= $( this.getElementWindow() )
6701 .on( 'resize', this.onClippableWindowResizeHandler
);
6702 // Initial clip after visible
6705 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6706 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6708 this.$clippableScrollableContainer
= null;
6709 this.$clippableScroller
.off( 'scroll', this.onClippableScrollHandler
);
6710 this.$clippableScroller
= null;
6711 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
6712 this.$clippableWindow
= null;
6720 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6722 * @return {boolean} Element will be clipped to the visible area
6724 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
6725 return this.clipping
;
6729 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6731 * @return {boolean} Part of the element is being clipped
6733 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
6734 return this.clippedHorizontally
|| this.clippedVertically
;
6738 * Check if the right of the element is being clipped by the nearest scrollable container.
6740 * @return {boolean} Part of the element is being clipped
6742 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
6743 return this.clippedHorizontally
;
6747 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6749 * @return {boolean} Part of the element is being clipped
6751 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
6752 return this.clippedVertically
;
6756 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6758 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6759 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6761 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
6762 this.idealWidth
= width
;
6763 this.idealHeight
= height
;
6765 if ( !this.clipping
) {
6766 // Update dimensions
6767 this.$clippable
.css( { width
: width
, height
: height
} );
6769 // While clipping, idealWidth and idealHeight are not considered
6773 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6774 * the element's natural height changes.
6776 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6777 * overlapped by, the visible area of the nearest scrollable container.
6781 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
6782 var $container
, extraHeight
, extraWidth
, ccOffset
,
6783 $scrollableContainer
, scOffset
, scHeight
, scWidth
,
6784 ccWidth
, scrollerIsWindow
, scrollTop
, scrollLeft
,
6785 desiredWidth
, desiredHeight
, allotedWidth
, allotedHeight
,
6786 naturalWidth
, naturalHeight
, clipWidth
, clipHeight
,
6787 buffer
= 7; // Chosen by fair dice roll
6789 if ( !this.clipping
) {
6790 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
6794 $container
= this.$clippableContainer
|| this.$clippable
;
6795 extraHeight
= $container
.outerHeight() - this.$clippable
.outerHeight();
6796 extraWidth
= $container
.outerWidth() - this.$clippable
.outerWidth();
6797 ccOffset
= $container
.offset();
6798 $scrollableContainer
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
6799 this.$clippableWindow
: this.$clippableScrollableContainer
;
6800 scOffset
= $scrollableContainer
.offset() || { top
: 0, left
: 0 };
6801 scHeight
= $scrollableContainer
.innerHeight() - buffer
;
6802 scWidth
= $scrollableContainer
.innerWidth() - buffer
;
6803 ccWidth
= $container
.outerWidth() + buffer
;
6804 scrollerIsWindow
= this.$clippableScroller
[ 0 ] === this.$clippableWindow
[ 0 ];
6805 scrollTop
= scrollerIsWindow
? this.$clippableScroller
.scrollTop() : 0;
6806 scrollLeft
= scrollerIsWindow
? this.$clippableScroller
.scrollLeft() : 0;
6807 desiredWidth
= ccOffset
.left
< 0 ?
6808 ccWidth
+ ccOffset
.left
:
6809 ( scOffset
.left
+ scrollLeft
+ scWidth
) - ccOffset
.left
;
6810 desiredHeight
= ( scOffset
.top
+ scrollTop
+ scHeight
) - ccOffset
.top
;
6811 allotedWidth
= desiredWidth
- extraWidth
;
6812 allotedHeight
= desiredHeight
- extraHeight
;
6813 naturalWidth
= this.$clippable
.prop( 'scrollWidth' );
6814 naturalHeight
= this.$clippable
.prop( 'scrollHeight' );
6815 clipWidth
= allotedWidth
< naturalWidth
;
6816 clipHeight
= allotedHeight
< naturalHeight
;
6819 this.$clippable
.css( { overflowX
: 'scroll', width
: Math
.max( 0, allotedWidth
) } );
6821 this.$clippable
.css( { width
: this.idealWidth
? this.idealWidth
- extraWidth
: '', overflowX
: '' } );
6824 this.$clippable
.css( { overflowY
: 'scroll', height
: Math
.max( 0, allotedHeight
) } );
6826 this.$clippable
.css( { height
: this.idealHeight
? this.idealHeight
- extraHeight
: '', overflowY
: '' } );
6829 // If we stopped clipping in at least one of the dimensions
6830 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
6831 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6834 this.clippedHorizontally
= clipWidth
;
6835 this.clippedVertically
= clipHeight
;
6841 * Element that will stick under a specified container, even when it is inserted elsewhere in the
6842 * document (for example, in a OO.ui.Window's $overlay).
6844 * The elements's position is automatically calculated and maintained when window is resized or the
6845 * page is scrolled. If you reposition the container manually, you have to call #position to make
6846 * sure the element is still placed correctly.
6848 * As positioning is only possible when both the element and the container are attached to the DOM
6849 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
6850 * the #toggle method to display a floating popup, for example.
6856 * @param {Object} [config] Configuration options
6857 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
6858 * @cfg {jQuery} [$floatableContainer] Node to position below
6860 OO
.ui
.mixin
.FloatableElement
= function OoUiMixinFloatableElement( config
) {
6861 // Configuration initialization
6862 config
= config
|| {};
6865 this.$floatable
= null;
6866 this.$floatableContainer
= null;
6867 this.$floatableWindow
= null;
6868 this.$floatableClosestScrollable
= null;
6869 this.onFloatableScrollHandler
= this.position
.bind( this );
6870 this.onFloatableWindowResizeHandler
= this.position
.bind( this );
6873 this.setFloatableContainer( config
.$floatableContainer
);
6874 this.setFloatableElement( config
.$floatable
|| this.$element
);
6880 * Set floatable element.
6882 * If an element is already set, it will be cleaned up before setting up the new element.
6884 * @param {jQuery} $floatable Element to make floatable
6886 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableElement = function ( $floatable
) {
6887 if ( this.$floatable
) {
6888 this.$floatable
.removeClass( 'oo-ui-floatableElement-floatable' );
6889 this.$floatable
.css( { left
: '', top
: '' } );
6892 this.$floatable
= $floatable
.addClass( 'oo-ui-floatableElement-floatable' );
6897 * Set floatable container.
6899 * The element will be always positioned under the specified container.
6901 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
6903 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableContainer = function ( $floatableContainer
) {
6904 this.$floatableContainer
= $floatableContainer
;
6905 if ( this.$floatable
) {
6911 * Toggle positioning.
6913 * Do not turn positioning on until after the element is attached to the DOM and visible.
6915 * @param {boolean} [positioning] Enable positioning, omit to toggle
6918 OO
.ui
.mixin
.FloatableElement
.prototype.togglePositioning = function ( positioning
) {
6919 var closestScrollableOfContainer
, closestScrollableOfFloatable
;
6921 positioning
= positioning
=== undefined ? !this.positioning
: !!positioning
;
6923 if ( this.positioning
!== positioning
) {
6924 this.positioning
= positioning
;
6926 closestScrollableOfContainer
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatableContainer
[ 0 ] );
6927 closestScrollableOfFloatable
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatable
[ 0 ] );
6928 if ( closestScrollableOfContainer
!== closestScrollableOfFloatable
) {
6929 // If the scrollable is the root, we have to listen to scroll events
6930 // on the window because of browser inconsistencies (or do we? someone should verify this)
6931 if ( $( closestScrollableOfContainer
).is( 'html, body' ) ) {
6932 closestScrollableOfContainer
= OO
.ui
.Element
.static.getWindow( closestScrollableOfContainer
);
6936 if ( positioning
) {
6937 this.$floatableWindow
= $( this.getElementWindow() );
6938 this.$floatableWindow
.on( 'resize', this.onFloatableWindowResizeHandler
);
6940 if ( closestScrollableOfContainer
!== closestScrollableOfFloatable
) {
6941 this.$floatableClosestScrollable
= $( closestScrollableOfContainer
);
6942 this.$floatableClosestScrollable
.on( 'scroll', this.onFloatableScrollHandler
);
6945 // Initial position after visible
6948 if ( this.$floatableWindow
) {
6949 this.$floatableWindow
.off( 'resize', this.onFloatableWindowResizeHandler
);
6950 this.$floatableWindow
= null;
6953 if ( this.$floatableClosestScrollable
) {
6954 this.$floatableClosestScrollable
.off( 'scroll', this.onFloatableScrollHandler
);
6955 this.$floatableClosestScrollable
= null;
6958 this.$floatable
.css( { left
: '', top
: '' } );
6966 * Position the floatable below its container.
6968 * This should only be done when both of them are attached to the DOM and visible.
6972 OO
.ui
.mixin
.FloatableElement
.prototype.position = function () {
6975 if ( !this.positioning
) {
6979 pos
= OO
.ui
.Element
.static.getRelativePosition( this.$floatableContainer
, this.$floatable
.offsetParent() );
6981 // Position under container
6982 pos
.top
+= this.$floatableContainer
.height();
6983 this.$floatable
.css( pos
);
6985 // We updated the position, so re-evaluate the clipping state.
6986 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
6987 // will not notice the need to update itself.)
6988 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
6989 // it not listen to the right events in the right places?
6998 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
6999 * Accesskeys allow an user to go to a specific element by using
7000 * a shortcut combination of a browser specific keys + the key
7004 * // AccessKeyedElement provides an 'accesskey' attribute to the
7005 * // ButtonWidget class
7006 * var button = new OO.ui.ButtonWidget( {
7007 * label: 'Button with Accesskey',
7010 * $( 'body' ).append( button.$element );
7016 * @param {Object} [config] Configuration options
7017 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
7018 * If this config is omitted, the accesskey functionality is applied to $element, the
7019 * element created by the class.
7020 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
7021 * this config is omitted, no accesskey will be added.
7023 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
7024 // Configuration initialization
7025 config
= config
|| {};
7028 this.$accessKeyed
= null;
7029 this.accessKey
= null;
7032 this.setAccessKey( config
.accessKey
|| null );
7033 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
7038 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
7040 /* Static Properties */
7043 * The access key, a function that returns a key, or `null` for no accesskey.
7047 * @property {string|Function|null}
7049 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
7054 * Set the accesskeyed element.
7056 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
7057 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
7059 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
7061 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
7062 if ( this.$accessKeyed
) {
7063 this.$accessKeyed
.removeAttr( 'accesskey' );
7066 this.$accessKeyed
= $accessKeyed
;
7067 if ( this.accessKey
) {
7068 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
7075 * @param {string|Function|null} accesskey Key, a function that returns a key, or `null` for no accesskey
7078 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
7079 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
7081 if ( this.accessKey
!== accessKey
) {
7082 if ( this.$accessKeyed
) {
7083 if ( accessKey
!== null ) {
7084 this.$accessKeyed
.attr( 'accesskey', accessKey
);
7086 this.$accessKeyed
.removeAttr( 'accesskey' );
7089 this.accessKey
= accessKey
;
7098 * @return {string} accessKey string
7100 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
7101 return this.accessKey
;
7105 * Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute {@link OO.ui.Toolbar toolbars}.
7106 * Each tool is configured with a static name, title, and icon and is customized with the command to carry
7107 * out when the tool is selected. Tools must also be registered with a {@link OO.ui.ToolFactory tool factory},
7108 * which creates the tools on demand.
7110 * Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup},
7111 * {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which determine how
7112 * the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an example.
7114 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
7115 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7119 * @extends OO.ui.Widget
7120 * @mixins OO.ui.mixin.IconElement
7121 * @mixins OO.ui.mixin.FlaggedElement
7122 * @mixins OO.ui.mixin.TabIndexedElement
7125 * @param {OO.ui.ToolGroup} toolGroup
7126 * @param {Object} [config] Configuration options
7127 * @cfg {string|Function} [title] Title text or a function that returns text. If this config is omitted, the value of
7128 * the {@link #static-title static title} property is used.
7130 * The title is used in different ways depending on the type of toolgroup that contains the tool. The
7131 * 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
7132 * part of a {@link OO.ui.ListToolGroup list} or {@link OO.ui.MenuToolGroup menu} toolgroup.
7134 * For bar toolgroups, a description of the accelerator key is appended to the title if an accelerator key
7135 * is associated with an action by the same name as the tool and accelerator functionality has been added to the application.
7136 * To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method.
7138 OO
.ui
.Tool
= function OoUiTool( toolGroup
, config
) {
7139 // Allow passing positional parameters inside the config object
7140 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
7142 toolGroup
= config
.toolGroup
;
7145 // Configuration initialization
7146 config
= config
|| {};
7148 // Parent constructor
7149 OO
.ui
.Tool
.parent
.call( this, config
);
7152 this.toolGroup
= toolGroup
;
7153 this.toolbar
= this.toolGroup
.getToolbar();
7154 this.active
= false;
7155 this.$title
= $( '<span>' );
7156 this.$accel
= $( '<span>' );
7157 this.$link
= $( '<a>' );
7160 // Mixin constructors
7161 OO
.ui
.mixin
.IconElement
.call( this, config
);
7162 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
7163 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$link
} ) );
7166 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
7169 this.$title
.addClass( 'oo-ui-tool-title' );
7171 .addClass( 'oo-ui-tool-accel' )
7173 // This may need to be changed if the key names are ever localized,
7174 // but for now they are essentially written in English
7179 .addClass( 'oo-ui-tool-link' )
7180 .append( this.$icon
, this.$title
, this.$accel
)
7181 .attr( 'role', 'button' );
7183 .data( 'oo-ui-tool', this )
7185 'oo-ui-tool ' + 'oo-ui-tool-name-' +
7186 this.constructor.static.name
.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
7188 .toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel
)
7189 .append( this.$link
);
7190 this.setTitle( config
.title
|| this.constructor.static.title
);
7195 OO
.inheritClass( OO
.ui
.Tool
, OO
.ui
.Widget
);
7196 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.IconElement
);
7197 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.FlaggedElement
);
7198 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.TabIndexedElement
);
7200 /* Static Properties */
7206 OO
.ui
.Tool
.static.tagName
= 'span';
7209 * Symbolic name of tool.
7211 * The symbolic name is used internally to register the tool with a {@link OO.ui.ToolFactory ToolFactory}. It can
7212 * also be used when adding tools to toolgroups.
7217 * @property {string}
7219 OO
.ui
.Tool
.static.name
= '';
7222 * Symbolic name of the group.
7224 * The group name is used to associate tools with each other so that they can be selected later by
7225 * a {@link OO.ui.ToolGroup toolgroup}.
7230 * @property {string}
7232 OO
.ui
.Tool
.static.group
= '';
7235 * 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.
7240 * @property {string|Function}
7242 OO
.ui
.Tool
.static.title
= '';
7245 * Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup.
7246 * Normally only the icon is displayed, or only the label if no icon is given.
7250 * @property {boolean}
7252 OO
.ui
.Tool
.static.displayBothIconAndLabel
= false;
7255 * Add tool to catch-all groups automatically.
7257 * A catch-all group, which contains all tools that do not currently belong to a toolgroup,
7258 * can be included in a toolgroup using the wildcard selector, an asterisk (*).
7262 * @property {boolean}
7264 OO
.ui
.Tool
.static.autoAddToCatchall
= true;
7267 * Add tool to named groups automatically.
7269 * By default, tools that are configured with a static ‘group’ property are added
7270 * to that group and will be selected when the symbolic name of the group is specified (e.g., when
7271 * toolgroups include tools by group name).
7274 * @property {boolean}
7277 OO
.ui
.Tool
.static.autoAddToGroup
= true;
7280 * Check if this tool is compatible with given data.
7282 * This is a stub that can be overriden to provide support for filtering tools based on an
7283 * arbitrary piece of information (e.g., where the cursor is in a document). The implementation
7284 * must also call this method so that the compatibility check can be performed.
7288 * @param {Mixed} data Data to check
7289 * @return {boolean} Tool can be used with data
7291 OO
.ui
.Tool
.static.isCompatibleWith = function () {
7298 * Handle the toolbar state being updated.
7300 * This is an abstract method that must be overridden in a concrete subclass.
7305 OO
.ui
.Tool
.prototype.onUpdateState = function () {
7307 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
7312 * Handle the tool being selected.
7314 * This is an abstract method that must be overridden in a concrete subclass.
7319 OO
.ui
.Tool
.prototype.onSelect = function () {
7321 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
7326 * Check if the tool is active.
7328 * Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed
7329 * with the #setActive method. Additional CSS is applied to the tool to reflect the active state.
7331 * @return {boolean} Tool is active
7333 OO
.ui
.Tool
.prototype.isActive = function () {
7338 * Make the tool appear active or inactive.
7340 * This method should be called within #onSelect or #onUpdateState event handlers to make the tool
7341 * appear pressed or not.
7343 * @param {boolean} state Make tool appear active
7345 OO
.ui
.Tool
.prototype.setActive = function ( state
) {
7346 this.active
= !!state
;
7347 if ( this.active
) {
7348 this.$element
.addClass( 'oo-ui-tool-active' );
7350 this.$element
.removeClass( 'oo-ui-tool-active' );
7355 * Set the tool #title.
7357 * @param {string|Function} title Title text or a function that returns text
7360 OO
.ui
.Tool
.prototype.setTitle = function ( title
) {
7361 this.title
= OO
.ui
.resolveMsg( title
);
7367 * Get the tool #title.
7369 * @return {string} Title text
7371 OO
.ui
.Tool
.prototype.getTitle = function () {
7376 * Get the tool's symbolic name.
7378 * @return {string} Symbolic name of tool
7380 OO
.ui
.Tool
.prototype.getName = function () {
7381 return this.constructor.static.name
;
7387 OO
.ui
.Tool
.prototype.updateTitle = function () {
7388 var titleTooltips
= this.toolGroup
.constructor.static.titleTooltips
,
7389 accelTooltips
= this.toolGroup
.constructor.static.accelTooltips
,
7390 accel
= this.toolbar
.getToolAccelerator( this.constructor.static.name
),
7393 this.$title
.text( this.title
);
7394 this.$accel
.text( accel
);
7396 if ( titleTooltips
&& typeof this.title
=== 'string' && this.title
.length
) {
7397 tooltipParts
.push( this.title
);
7399 if ( accelTooltips
&& typeof accel
=== 'string' && accel
.length
) {
7400 tooltipParts
.push( accel
);
7402 if ( tooltipParts
.length
) {
7403 this.$link
.attr( 'title', tooltipParts
.join( ' ' ) );
7405 this.$link
.removeAttr( 'title' );
7412 * Destroying the tool removes all event handlers and the tool’s DOM elements.
7413 * Call this method whenever you are done using a tool.
7415 OO
.ui
.Tool
.prototype.destroy = function () {
7416 this.toolbar
.disconnect( this );
7417 this.$element
.remove();
7421 * Toolbars are complex interface components that permit users to easily access a variety
7422 * of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional commands that are
7423 * part of the toolbar, but not configured as tools.
7425 * Individual tools are customized and then registered with a {@link OO.ui.ToolFactory tool factory}, which creates
7426 * the tools on demand. Each tool has a symbolic name (used when registering the tool), a title (e.g., ‘Insert
7427 * picture’), and an icon.
7429 * Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be {@link OO.ui.MenuToolGroup menus}
7430 * of tools, {@link OO.ui.ListToolGroup lists} of tools, or a single {@link OO.ui.BarToolGroup bar} of tools.
7431 * The arrangement and order of the toolgroups is customized when the toolbar is set up. Tools can be presented in
7432 * any order, but each can only appear once in the toolbar.
7434 * The following is an example of a basic toolbar.
7437 * // Example of a toolbar
7438 * // Create the toolbar
7439 * var toolFactory = new OO.ui.ToolFactory();
7440 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7441 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7443 * // We will be placing status text in this element when tools are used
7444 * var $area = $( '<p>' ).text( 'Toolbar example' );
7446 * // Define the tools that we're going to place in our toolbar
7448 * // Create a class inheriting from OO.ui.Tool
7449 * function PictureTool() {
7450 * PictureTool.parent.apply( this, arguments );
7452 * OO.inheritClass( PictureTool, OO.ui.Tool );
7453 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7454 * // of 'icon' and 'title' (displayed icon and text).
7455 * PictureTool.static.name = 'picture';
7456 * PictureTool.static.icon = 'picture';
7457 * PictureTool.static.title = 'Insert picture';
7458 * // Defines the action that will happen when this tool is selected (clicked).
7459 * PictureTool.prototype.onSelect = function () {
7460 * $area.text( 'Picture tool clicked!' );
7461 * // Never display this tool as "active" (selected).
7462 * this.setActive( false );
7464 * // Make this tool available in our toolFactory and thus our toolbar
7465 * toolFactory.register( PictureTool );
7467 * // Register two more tools, nothing interesting here
7468 * function SettingsTool() {
7469 * SettingsTool.parent.apply( this, arguments );
7471 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7472 * SettingsTool.static.name = 'settings';
7473 * SettingsTool.static.icon = 'settings';
7474 * SettingsTool.static.title = 'Change settings';
7475 * SettingsTool.prototype.onSelect = function () {
7476 * $area.text( 'Settings tool clicked!' );
7477 * this.setActive( false );
7479 * toolFactory.register( SettingsTool );
7481 * // Register two more tools, nothing interesting here
7482 * function StuffTool() {
7483 * StuffTool.parent.apply( this, arguments );
7485 * OO.inheritClass( StuffTool, OO.ui.Tool );
7486 * StuffTool.static.name = 'stuff';
7487 * StuffTool.static.icon = 'ellipsis';
7488 * StuffTool.static.title = 'More stuff';
7489 * StuffTool.prototype.onSelect = function () {
7490 * $area.text( 'More stuff tool clicked!' );
7491 * this.setActive( false );
7493 * toolFactory.register( StuffTool );
7495 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7496 * // little popup window (a PopupWidget).
7497 * function HelpTool( toolGroup, config ) {
7498 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7503 * this.popup.$body.append( '<p>I am helpful!</p>' );
7505 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7506 * HelpTool.static.name = 'help';
7507 * HelpTool.static.icon = 'help';
7508 * HelpTool.static.title = 'Help';
7509 * toolFactory.register( HelpTool );
7511 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7512 * // used once (but not all defined tools must be used).
7515 * // 'bar' tool groups display tools' icons only, side-by-side.
7517 * include: [ 'picture', 'help' ]
7520 * // 'list' tool groups display both the titles and icons, in a dropdown list.
7522 * indicator: 'down',
7524 * include: [ 'settings', 'stuff' ]
7526 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
7527 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here,
7528 * // since it's more complicated to use. (See the next example snippet on this page.)
7531 * // Create some UI around the toolbar and place it in the document
7532 * var frame = new OO.ui.PanelLayout( {
7536 * var contentFrame = new OO.ui.PanelLayout( {
7540 * frame.$element.append(
7542 * contentFrame.$element.append( $area )
7544 * $( 'body' ).append( frame.$element );
7546 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7548 * toolbar.initialize();
7550 * The following example extends the previous one to illustrate 'menu' toolgroups and the usage of
7551 * 'updateState' event.
7554 * // Create the toolbar
7555 * var toolFactory = new OO.ui.ToolFactory();
7556 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7557 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7559 * // We will be placing status text in this element when tools are used
7560 * var $area = $( '<p>' ).text( 'Toolbar example' );
7562 * // Define the tools that we're going to place in our toolbar
7564 * // Create a class inheriting from OO.ui.Tool
7565 * function PictureTool() {
7566 * PictureTool.parent.apply( this, arguments );
7568 * OO.inheritClass( PictureTool, OO.ui.Tool );
7569 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7570 * // of 'icon' and 'title' (displayed icon and text).
7571 * PictureTool.static.name = 'picture';
7572 * PictureTool.static.icon = 'picture';
7573 * PictureTool.static.title = 'Insert picture';
7574 * // Defines the action that will happen when this tool is selected (clicked).
7575 * PictureTool.prototype.onSelect = function () {
7576 * $area.text( 'Picture tool clicked!' );
7577 * // Never display this tool as "active" (selected).
7578 * this.setActive( false );
7580 * // The toolbar can be synchronized with the state of some external stuff, like a text
7581 * // editor's editing area, highlighting the tools (e.g. a 'bold' tool would be shown as active
7582 * // when the text cursor was inside bolded text). Here we simply disable this feature.
7583 * PictureTool.prototype.onUpdateState = function () {
7585 * // Make this tool available in our toolFactory and thus our toolbar
7586 * toolFactory.register( PictureTool );
7588 * // Register two more tools, nothing interesting here
7589 * function SettingsTool() {
7590 * SettingsTool.parent.apply( this, arguments );
7591 * this.reallyActive = false;
7593 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7594 * SettingsTool.static.name = 'settings';
7595 * SettingsTool.static.icon = 'settings';
7596 * SettingsTool.static.title = 'Change settings';
7597 * SettingsTool.prototype.onSelect = function () {
7598 * $area.text( 'Settings tool clicked!' );
7599 * // Toggle the active state on each click
7600 * this.reallyActive = !this.reallyActive;
7601 * this.setActive( this.reallyActive );
7602 * // To update the menu label
7603 * this.toolbar.emit( 'updateState' );
7605 * SettingsTool.prototype.onUpdateState = function () {
7607 * toolFactory.register( SettingsTool );
7609 * // Register two more tools, nothing interesting here
7610 * function StuffTool() {
7611 * StuffTool.parent.apply( this, arguments );
7612 * this.reallyActive = false;
7614 * OO.inheritClass( StuffTool, OO.ui.Tool );
7615 * StuffTool.static.name = 'stuff';
7616 * StuffTool.static.icon = 'ellipsis';
7617 * StuffTool.static.title = 'More stuff';
7618 * StuffTool.prototype.onSelect = function () {
7619 * $area.text( 'More stuff tool clicked!' );
7620 * // Toggle the active state on each click
7621 * this.reallyActive = !this.reallyActive;
7622 * this.setActive( this.reallyActive );
7623 * // To update the menu label
7624 * this.toolbar.emit( 'updateState' );
7626 * StuffTool.prototype.onUpdateState = function () {
7628 * toolFactory.register( StuffTool );
7630 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7631 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
7632 * function HelpTool( toolGroup, config ) {
7633 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7638 * this.popup.$body.append( '<p>I am helpful!</p>' );
7640 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7641 * HelpTool.static.name = 'help';
7642 * HelpTool.static.icon = 'help';
7643 * HelpTool.static.title = 'Help';
7644 * toolFactory.register( HelpTool );
7646 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7647 * // used once (but not all defined tools must be used).
7650 * // 'bar' tool groups display tools' icons only, side-by-side.
7652 * include: [ 'picture', 'help' ]
7655 * // 'menu' tool groups display both the titles and icons, in a dropdown menu.
7656 * // Menu label indicates which items are selected.
7658 * indicator: 'down',
7659 * include: [ 'settings', 'stuff' ]
7663 * // Create some UI around the toolbar and place it in the document
7664 * var frame = new OO.ui.PanelLayout( {
7668 * var contentFrame = new OO.ui.PanelLayout( {
7672 * frame.$element.append(
7674 * contentFrame.$element.append( $area )
7676 * $( 'body' ).append( frame.$element );
7678 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7680 * toolbar.initialize();
7681 * toolbar.emit( 'updateState' );
7684 * @extends OO.ui.Element
7685 * @mixins OO.EventEmitter
7686 * @mixins OO.ui.mixin.GroupElement
7689 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
7690 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups
7691 * @param {Object} [config] Configuration options
7692 * @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are included
7693 * in the toolbar, but are not configured as tools. By default, actions are displayed on the right side of
7695 * @cfg {boolean} [shadow] Add a shadow below the toolbar.
7697 OO
.ui
.Toolbar
= function OoUiToolbar( toolFactory
, toolGroupFactory
, config
) {
7698 // Allow passing positional parameters inside the config object
7699 if ( OO
.isPlainObject( toolFactory
) && config
=== undefined ) {
7700 config
= toolFactory
;
7701 toolFactory
= config
.toolFactory
;
7702 toolGroupFactory
= config
.toolGroupFactory
;
7705 // Configuration initialization
7706 config
= config
|| {};
7708 // Parent constructor
7709 OO
.ui
.Toolbar
.parent
.call( this, config
);
7711 // Mixin constructors
7712 OO
.EventEmitter
.call( this );
7713 OO
.ui
.mixin
.GroupElement
.call( this, config
);
7716 this.toolFactory
= toolFactory
;
7717 this.toolGroupFactory
= toolGroupFactory
;
7720 this.$bar
= $( '<div>' );
7721 this.$actions
= $( '<div>' );
7722 this.initialized
= false;
7723 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
7727 .add( this.$bar
).add( this.$group
).add( this.$actions
)
7728 .on( 'mousedown keydown', this.onPointerDown
.bind( this ) );
7731 this.$group
.addClass( 'oo-ui-toolbar-tools' );
7732 if ( config
.actions
) {
7733 this.$bar
.append( this.$actions
.addClass( 'oo-ui-toolbar-actions' ) );
7736 .addClass( 'oo-ui-toolbar-bar' )
7737 .append( this.$group
, '<div style="clear:both"></div>' );
7738 if ( config
.shadow
) {
7739 this.$bar
.append( '<div class="oo-ui-toolbar-shadow"></div>' );
7741 this.$element
.addClass( 'oo-ui-toolbar' ).append( this.$bar
);
7746 OO
.inheritClass( OO
.ui
.Toolbar
, OO
.ui
.Element
);
7747 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.EventEmitter
);
7748 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.ui
.mixin
.GroupElement
);
7753 * Get the tool factory.
7755 * @return {OO.ui.ToolFactory} Tool factory
7757 OO
.ui
.Toolbar
.prototype.getToolFactory = function () {
7758 return this.toolFactory
;
7762 * Get the toolgroup factory.
7764 * @return {OO.Factory} Toolgroup factory
7766 OO
.ui
.Toolbar
.prototype.getToolGroupFactory = function () {
7767 return this.toolGroupFactory
;
7771 * Handles mouse down events.
7774 * @param {jQuery.Event} e Mouse down event
7776 OO
.ui
.Toolbar
.prototype.onPointerDown = function ( e
) {
7777 var $closestWidgetToEvent
= $( e
.target
).closest( '.oo-ui-widget' ),
7778 $closestWidgetToToolbar
= this.$element
.closest( '.oo-ui-widget' );
7779 if ( !$closestWidgetToEvent
.length
|| $closestWidgetToEvent
[ 0 ] === $closestWidgetToToolbar
[ 0 ] ) {
7785 * Handle window resize event.
7788 * @param {jQuery.Event} e Window resize event
7790 OO
.ui
.Toolbar
.prototype.onWindowResize = function () {
7791 this.$element
.toggleClass(
7792 'oo-ui-toolbar-narrow',
7793 this.$bar
.width() <= this.narrowThreshold
7798 * Sets up handles and preloads required information for the toolbar to work.
7799 * This must be called after it is attached to a visible document and before doing anything else.
7801 OO
.ui
.Toolbar
.prototype.initialize = function () {
7802 if ( !this.initialized
) {
7803 this.initialized
= true;
7804 this.narrowThreshold
= this.$group
.width() + this.$actions
.width();
7805 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
7806 this.onWindowResize();
7811 * Set up the toolbar.
7813 * The toolbar is set up with a list of toolgroup configurations that specify the type of
7814 * toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or {@link OO.ui.ListToolGroup list})
7815 * to add and which tools to include, exclude, promote, or demote within that toolgroup. Please
7816 * see {@link OO.ui.ToolGroup toolgroups} for more information about including tools in toolgroups.
7818 * @param {Object.<string,Array>} groups List of toolgroup configurations
7819 * @param {Array|string} [groups.include] Tools to include in the toolgroup
7820 * @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup
7821 * @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup
7822 * @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup
7824 OO
.ui
.Toolbar
.prototype.setup = function ( groups
) {
7825 var i
, len
, type
, group
,
7827 defaultType
= 'bar';
7829 // Cleanup previous groups
7832 // Build out new groups
7833 for ( i
= 0, len
= groups
.length
; i
< len
; i
++ ) {
7834 group
= groups
[ i
];
7835 if ( group
.include
=== '*' ) {
7836 // Apply defaults to catch-all groups
7837 if ( group
.type
=== undefined ) {
7838 group
.type
= 'list';
7840 if ( group
.label
=== undefined ) {
7841 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
7844 // Check type has been registered
7845 type
= this.getToolGroupFactory().lookup( group
.type
) ? group
.type
: defaultType
;
7847 this.getToolGroupFactory().create( type
, this, group
)
7850 this.addItems( items
);
7854 * Remove all tools and toolgroups from the toolbar.
7856 OO
.ui
.Toolbar
.prototype.reset = function () {
7861 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
7862 this.items
[ i
].destroy();
7868 * Destroy the toolbar.
7870 * Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. Call
7871 * this method whenever you are done using a toolbar.
7873 OO
.ui
.Toolbar
.prototype.destroy = function () {
7874 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
7876 this.$element
.remove();
7880 * Check if the tool is available.
7882 * Available tools are ones that have not yet been added to the toolbar.
7884 * @param {string} name Symbolic name of tool
7885 * @return {boolean} Tool is available
7887 OO
.ui
.Toolbar
.prototype.isToolAvailable = function ( name
) {
7888 return !this.tools
[ name
];
7892 * Prevent tool from being used again.
7894 * @param {OO.ui.Tool} tool Tool to reserve
7896 OO
.ui
.Toolbar
.prototype.reserveTool = function ( tool
) {
7897 this.tools
[ tool
.getName() ] = tool
;
7901 * Allow tool to be used again.
7903 * @param {OO.ui.Tool} tool Tool to release
7905 OO
.ui
.Toolbar
.prototype.releaseTool = function ( tool
) {
7906 delete this.tools
[ tool
.getName() ];
7910 * Get accelerator label for tool.
7912 * The OOjs UI library does not contain an accelerator system, but this is the hook for one. To
7913 * use an accelerator system, subclass the toolbar and override this method, which is meant to return a label
7914 * that describes the accelerator keys for the tool passed (by symbolic name) to the method.
7916 * @param {string} name Symbolic name of tool
7917 * @return {string|undefined} Tool accelerator label if available
7919 OO
.ui
.Toolbar
.prototype.getToolAccelerator = function () {
7924 * ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a {@link OO.ui.Toolbar toolbar}.
7925 * The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or {@link OO.ui.MenuToolGroup menu})
7926 * to which a tool belongs determines how the tool is arranged and displayed in the toolbar. Toolgroups
7927 * themselves are created on demand with a {@link OO.ui.ToolGroupFactory toolgroup factory}.
7929 * Toolgroups can contain individual tools, groups of tools, or all available tools:
7931 * To include an individual tool (or array of individual tools), specify tools by symbolic name:
7933 * include: [ 'tool-name' ] or [ { name: 'tool-name' }]
7935 * 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.)
7937 * include: [ { group: 'group-name' } ]
7939 * To include all tools that are not yet assigned to a toolgroup, use the catch-all selector, an asterisk (*):
7943 * See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in general,
7944 * please see the [OOjs UI documentation on MediaWiki][1].
7946 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7950 * @extends OO.ui.Widget
7951 * @mixins OO.ui.mixin.GroupElement
7954 * @param {OO.ui.Toolbar} toolbar
7955 * @param {Object} [config] Configuration options
7956 * @cfg {Array|string} [include=[]] List of tools to include in the toolgroup.
7957 * @cfg {Array|string} [exclude=[]] List of tools to exclude from the toolgroup.
7958 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning of the toolgroup.
7959 * @cfg {Array|string} [demote=[]] List of tools to demote to the end of the toolgroup.
7960 * This setting is particularly useful when tools have been added to the toolgroup
7961 * en masse (e.g., via the catch-all selector).
7963 OO
.ui
.ToolGroup
= function OoUiToolGroup( toolbar
, config
) {
7964 // Allow passing positional parameters inside the config object
7965 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
7967 toolbar
= config
.toolbar
;
7970 // Configuration initialization
7971 config
= config
|| {};
7973 // Parent constructor
7974 OO
.ui
.ToolGroup
.parent
.call( this, config
);
7976 // Mixin constructors
7977 OO
.ui
.mixin
.GroupElement
.call( this, config
);
7980 this.toolbar
= toolbar
;
7982 this.pressed
= null;
7983 this.autoDisabled
= false;
7984 this.include
= config
.include
|| [];
7985 this.exclude
= config
.exclude
|| [];
7986 this.promote
= config
.promote
|| [];
7987 this.demote
= config
.demote
|| [];
7988 this.onCapturedMouseKeyUpHandler
= this.onCapturedMouseKeyUp
.bind( this );
7992 mousedown
: this.onMouseKeyDown
.bind( this ),
7993 mouseup
: this.onMouseKeyUp
.bind( this ),
7994 keydown
: this.onMouseKeyDown
.bind( this ),
7995 keyup
: this.onMouseKeyUp
.bind( this ),
7996 focus
: this.onMouseOverFocus
.bind( this ),
7997 blur
: this.onMouseOutBlur
.bind( this ),
7998 mouseover
: this.onMouseOverFocus
.bind( this ),
7999 mouseout
: this.onMouseOutBlur
.bind( this )
8001 this.toolbar
.getToolFactory().connect( this, { register
: 'onToolFactoryRegister' } );
8002 this.aggregate( { disable
: 'itemDisable' } );
8003 this.connect( this, { itemDisable
: 'updateDisabled' } );
8006 this.$group
.addClass( 'oo-ui-toolGroup-tools' );
8008 .addClass( 'oo-ui-toolGroup' )
8009 .append( this.$group
);
8015 OO
.inheritClass( OO
.ui
.ToolGroup
, OO
.ui
.Widget
);
8016 OO
.mixinClass( OO
.ui
.ToolGroup
, OO
.ui
.mixin
.GroupElement
);
8024 /* Static Properties */
8027 * Show labels in tooltips.
8031 * @property {boolean}
8033 OO
.ui
.ToolGroup
.static.titleTooltips
= false;
8036 * Show acceleration labels in tooltips.
8038 * Note: The OOjs UI library does not include an accelerator system, but does contain
8039 * a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and
8040 * override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is
8041 * meant to return a label that describes the accelerator keys for a given tool (e.g., 'Ctrl + M').
8045 * @property {boolean}
8047 OO
.ui
.ToolGroup
.static.accelTooltips
= false;
8050 * Automatically disable the toolgroup when all tools are disabled
8054 * @property {boolean}
8056 OO
.ui
.ToolGroup
.static.autoDisable
= true;
8063 OO
.ui
.ToolGroup
.prototype.isDisabled = function () {
8064 return this.autoDisabled
|| OO
.ui
.ToolGroup
.parent
.prototype.isDisabled
.apply( this, arguments
);
8070 OO
.ui
.ToolGroup
.prototype.updateDisabled = function () {
8071 var i
, item
, allDisabled
= true;
8073 if ( this.constructor.static.autoDisable
) {
8074 for ( i
= this.items
.length
- 1; i
>= 0; i
-- ) {
8075 item
= this.items
[ i
];
8076 if ( !item
.isDisabled() ) {
8077 allDisabled
= false;
8081 this.autoDisabled
= allDisabled
;
8083 OO
.ui
.ToolGroup
.parent
.prototype.updateDisabled
.apply( this, arguments
);
8087 * Handle mouse down and key down events.
8090 * @param {jQuery.Event} e Mouse down or key down event
8092 OO
.ui
.ToolGroup
.prototype.onMouseKeyDown = function ( e
) {
8094 !this.isDisabled() &&
8095 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
8097 this.pressed
= this.getTargetTool( e
);
8098 if ( this.pressed
) {
8099 this.pressed
.setActive( true );
8100 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler
);
8101 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler
);
8108 * Handle captured mouse up and key up events.
8111 * @param {Event} e Mouse up or key up event
8113 OO
.ui
.ToolGroup
.prototype.onCapturedMouseKeyUp = function ( e
) {
8114 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler
);
8115 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler
);
8116 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
8117 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
8118 this.onMouseKeyUp( e
);
8122 * Handle mouse up and key up events.
8125 * @param {jQuery.Event} e Mouse up or key up event
8127 OO
.ui
.ToolGroup
.prototype.onMouseKeyUp = function ( e
) {
8128 var tool
= this.getTargetTool( e
);
8131 !this.isDisabled() && this.pressed
&& this.pressed
=== tool
&&
8132 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
8134 this.pressed
.onSelect();
8135 this.pressed
= null;
8139 this.pressed
= null;
8143 * Handle mouse over and focus events.
8146 * @param {jQuery.Event} e Mouse over or focus event
8148 OO
.ui
.ToolGroup
.prototype.onMouseOverFocus = function ( e
) {
8149 var tool
= this.getTargetTool( e
);
8151 if ( this.pressed
&& this.pressed
=== tool
) {
8152 this.pressed
.setActive( true );
8157 * Handle mouse out and blur events.
8160 * @param {jQuery.Event} e Mouse out or blur event
8162 OO
.ui
.ToolGroup
.prototype.onMouseOutBlur = function ( e
) {
8163 var tool
= this.getTargetTool( e
);
8165 if ( this.pressed
&& this.pressed
=== tool
) {
8166 this.pressed
.setActive( false );
8171 * Get the closest tool to a jQuery.Event.
8173 * Only tool links are considered, which prevents other elements in the tool such as popups from
8174 * triggering tool group interactions.
8177 * @param {jQuery.Event} e
8178 * @return {OO.ui.Tool|null} Tool, `null` if none was found
8180 OO
.ui
.ToolGroup
.prototype.getTargetTool = function ( e
) {
8182 $item
= $( e
.target
).closest( '.oo-ui-tool-link' );
8184 if ( $item
.length
) {
8185 tool
= $item
.parent().data( 'oo-ui-tool' );
8188 return tool
&& !tool
.isDisabled() ? tool
: null;
8192 * Handle tool registry register events.
8194 * If a tool is registered after the group is created, we must repopulate the list to account for:
8196 * - a tool being added that may be included
8197 * - a tool already included being overridden
8200 * @param {string} name Symbolic name of tool
8202 OO
.ui
.ToolGroup
.prototype.onToolFactoryRegister = function () {
8207 * Get the toolbar that contains the toolgroup.
8209 * @return {OO.ui.Toolbar} Toolbar that contains the toolgroup
8211 OO
.ui
.ToolGroup
.prototype.getToolbar = function () {
8212 return this.toolbar
;
8216 * Add and remove tools based on configuration.
8218 OO
.ui
.ToolGroup
.prototype.populate = function () {
8219 var i
, len
, name
, tool
,
8220 toolFactory
= this.toolbar
.getToolFactory(),
8224 list
= this.toolbar
.getToolFactory().getTools(
8225 this.include
, this.exclude
, this.promote
, this.demote
8228 // Build a list of needed tools
8229 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
8233 toolFactory
.lookup( name
) &&
8234 // Tool is available or is already in this group
8235 ( this.toolbar
.isToolAvailable( name
) || this.tools
[ name
] )
8237 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
8238 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
8239 this.toolbar
.tools
[ name
] = true;
8240 tool
= this.tools
[ name
];
8242 // Auto-initialize tools on first use
8243 this.tools
[ name
] = tool
= toolFactory
.create( name
, this );
8246 this.toolbar
.reserveTool( tool
);
8248 names
[ name
] = true;
8251 // Remove tools that are no longer needed
8252 for ( name
in this.tools
) {
8253 if ( !names
[ name
] ) {
8254 this.tools
[ name
].destroy();
8255 this.toolbar
.releaseTool( this.tools
[ name
] );
8256 remove
.push( this.tools
[ name
] );
8257 delete this.tools
[ name
];
8260 if ( remove
.length
) {
8261 this.removeItems( remove
);
8263 // Update emptiness state
8265 this.$element
.removeClass( 'oo-ui-toolGroup-empty' );
8267 this.$element
.addClass( 'oo-ui-toolGroup-empty' );
8269 // Re-add tools (moving existing ones to new locations)
8270 this.addItems( add
);
8271 // Disabled state may depend on items
8272 this.updateDisabled();
8276 * Destroy toolgroup.
8278 OO
.ui
.ToolGroup
.prototype.destroy = function () {
8282 this.toolbar
.getToolFactory().disconnect( this );
8283 for ( name
in this.tools
) {
8284 this.toolbar
.releaseTool( this.tools
[ name
] );
8285 this.tools
[ name
].disconnect( this ).destroy();
8286 delete this.tools
[ name
];
8288 this.$element
.remove();
8292 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
8293 * consists of a header that contains the dialog title, a body with the message, and a footer that
8294 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
8295 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
8297 * There are two basic types of message dialogs, confirmation and alert:
8299 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
8300 * more details about the consequences.
8301 * - **alert**: the dialog title describes which event occurred and the message provides more information
8302 * about why the event occurred.
8304 * The MessageDialog class specifies two actions: ‘accept’, the primary
8305 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
8306 * passing along the selected action.
8308 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
8311 * // Example: Creating and opening a message dialog window.
8312 * var messageDialog = new OO.ui.MessageDialog();
8314 * // Create and append a window manager.
8315 * var windowManager = new OO.ui.WindowManager();
8316 * $( 'body' ).append( windowManager.$element );
8317 * windowManager.addWindows( [ messageDialog ] );
8318 * // Open the window.
8319 * windowManager.openWindow( messageDialog, {
8320 * title: 'Basic message dialog',
8321 * message: 'This is the message'
8324 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
8327 * @extends OO.ui.Dialog
8330 * @param {Object} [config] Configuration options
8332 OO
.ui
.MessageDialog
= function OoUiMessageDialog( config
) {
8333 // Parent constructor
8334 OO
.ui
.MessageDialog
.parent
.call( this, config
);
8337 this.verticalActionLayout
= null;
8340 this.$element
.addClass( 'oo-ui-messageDialog' );
8345 OO
.inheritClass( OO
.ui
.MessageDialog
, OO
.ui
.Dialog
);
8347 /* Static Properties */
8349 OO
.ui
.MessageDialog
.static.name
= 'message';
8351 OO
.ui
.MessageDialog
.static.size
= 'small';
8353 OO
.ui
.MessageDialog
.static.verbose
= false;
8358 * The title of a confirmation dialog describes what a progressive action will do. The
8359 * title of an alert dialog describes which event occurred.
8363 * @property {jQuery|string|Function|null}
8365 OO
.ui
.MessageDialog
.static.title
= null;
8368 * The message displayed in the dialog body.
8370 * A confirmation message describes the consequences of a progressive action. An alert
8371 * message describes why an event occurred.
8375 * @property {jQuery|string|Function|null}
8377 OO
.ui
.MessageDialog
.static.message
= null;
8379 OO
.ui
.MessageDialog
.static.actions
= [
8380 { action
: 'accept', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-accept' ), flags
: 'primary' },
8381 { action
: 'reject', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-reject' ), flags
: 'safe' }
8389 OO
.ui
.MessageDialog
.prototype.setManager = function ( manager
) {
8390 OO
.ui
.MessageDialog
.parent
.prototype.setManager
.call( this, manager
);
8393 this.manager
.connect( this, {
8403 OO
.ui
.MessageDialog
.prototype.onActionResize = function ( action
) {
8405 return OO
.ui
.MessageDialog
.parent
.prototype.onActionResize
.call( this, action
);
8409 * Handle window resized events.
8413 OO
.ui
.MessageDialog
.prototype.onResize = function () {
8415 dialog
.fitActions();
8416 // Wait for CSS transition to finish and do it again :(
8417 setTimeout( function () {
8418 dialog
.fitActions();
8423 * Toggle action layout between vertical and horizontal.
8426 * @param {boolean} [value] Layout actions vertically, omit to toggle
8429 OO
.ui
.MessageDialog
.prototype.toggleVerticalActionLayout = function ( value
) {
8430 value
= value
=== undefined ? !this.verticalActionLayout
: !!value
;
8432 if ( value
!== this.verticalActionLayout
) {
8433 this.verticalActionLayout
= value
;
8435 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value
)
8436 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value
);
8445 OO
.ui
.MessageDialog
.prototype.getActionProcess = function ( action
) {
8447 return new OO
.ui
.Process( function () {
8448 this.close( { action
: action
} );
8451 return OO
.ui
.MessageDialog
.parent
.prototype.getActionProcess
.call( this, action
);
8457 * @param {Object} [data] Dialog opening data
8458 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
8459 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
8460 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
8461 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
8464 OO
.ui
.MessageDialog
.prototype.getSetupProcess = function ( data
) {
8468 return OO
.ui
.MessageDialog
.parent
.prototype.getSetupProcess
.call( this, data
)
8469 .next( function () {
8470 this.title
.setLabel(
8471 data
.title
!== undefined ? data
.title
: this.constructor.static.title
8473 this.message
.setLabel(
8474 data
.message
!== undefined ? data
.message
: this.constructor.static.message
8476 this.message
.$element
.toggleClass(
8477 'oo-ui-messageDialog-message-verbose',
8478 data
.verbose
!== undefined ? data
.verbose
: this.constructor.static.verbose
8486 OO
.ui
.MessageDialog
.prototype.getReadyProcess = function ( data
) {
8490 return OO
.ui
.MessageDialog
.parent
.prototype.getReadyProcess
.call( this, data
)
8491 .next( function () {
8492 // Focus the primary action button
8493 var actions
= this.actions
.get();
8494 actions
= actions
.filter( function ( action
) {
8495 return action
.getFlags().indexOf( 'primary' ) > -1;
8497 if ( actions
.length
> 0 ) {
8498 actions
[ 0 ].$button
.focus();
8506 OO
.ui
.MessageDialog
.prototype.getBodyHeight = function () {
8507 var bodyHeight
, oldOverflow
,
8508 $scrollable
= this.container
.$element
;
8510 oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
8511 $scrollable
[ 0 ].style
.overflow
= 'hidden';
8513 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
8515 bodyHeight
= this.text
.$element
.outerHeight( true );
8516 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
8524 OO
.ui
.MessageDialog
.prototype.setDimensions = function ( dim
) {
8525 var $scrollable
= this.container
.$element
;
8526 OO
.ui
.MessageDialog
.parent
.prototype.setDimensions
.call( this, dim
);
8528 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
8529 // Need to do it after transition completes (250ms), add 50ms just in case.
8530 setTimeout( function () {
8531 var oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
8532 $scrollable
[ 0 ].style
.overflow
= 'hidden';
8534 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
8536 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
8545 OO
.ui
.MessageDialog
.prototype.initialize = function () {
8547 OO
.ui
.MessageDialog
.parent
.prototype.initialize
.call( this );
8550 this.$actions
= $( '<div>' );
8551 this.container
= new OO
.ui
.PanelLayout( {
8552 scrollable
: true, classes
: [ 'oo-ui-messageDialog-container' ]
8554 this.text
= new OO
.ui
.PanelLayout( {
8555 padded
: true, expanded
: false, classes
: [ 'oo-ui-messageDialog-text' ]
8557 this.message
= new OO
.ui
.LabelWidget( {
8558 classes
: [ 'oo-ui-messageDialog-message' ]
8562 this.title
.$element
.addClass( 'oo-ui-messageDialog-title' );
8563 this.$content
.addClass( 'oo-ui-messageDialog-content' );
8564 this.container
.$element
.append( this.text
.$element
);
8565 this.text
.$element
.append( this.title
.$element
, this.message
.$element
);
8566 this.$body
.append( this.container
.$element
);
8567 this.$actions
.addClass( 'oo-ui-messageDialog-actions' );
8568 this.$foot
.append( this.$actions
);
8574 OO
.ui
.MessageDialog
.prototype.attachActions = function () {
8575 var i
, len
, other
, special
, others
;
8578 OO
.ui
.MessageDialog
.parent
.prototype.attachActions
.call( this );
8580 special
= this.actions
.getSpecial();
8581 others
= this.actions
.getOthers();
8583 if ( special
.safe
) {
8584 this.$actions
.append( special
.safe
.$element
);
8585 special
.safe
.toggleFramed( false );
8587 if ( others
.length
) {
8588 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
8589 other
= others
[ i
];
8590 this.$actions
.append( other
.$element
);
8591 other
.toggleFramed( false );
8594 if ( special
.primary
) {
8595 this.$actions
.append( special
.primary
.$element
);
8596 special
.primary
.toggleFramed( false );
8599 if ( !this.isOpening() ) {
8600 // If the dialog is currently opening, this will be called automatically soon.
8601 // This also calls #fitActions.
8607 * Fit action actions into columns or rows.
8609 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
8613 OO
.ui
.MessageDialog
.prototype.fitActions = function () {
8615 previous
= this.verticalActionLayout
,
8616 actions
= this.actions
.get();
8619 this.toggleVerticalActionLayout( false );
8620 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
8621 action
= actions
[ i
];
8622 if ( action
.$element
.innerWidth() < action
.$label
.outerWidth( true ) ) {
8623 this.toggleVerticalActionLayout( true );
8628 // Move the body out of the way of the foot
8629 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
8631 if ( this.verticalActionLayout
!== previous
) {
8632 // We changed the layout, window height might need to be updated.
8638 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
8639 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
8640 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
8641 * relevant. The ProcessDialog class is always extended and customized with the actions and content
8642 * required for each process.
8644 * The process dialog box consists of a header that visually represents the ‘working’ state of long
8645 * processes with an animation. The header contains the dialog title as well as
8646 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
8647 * a ‘primary’ action on the right (e.g., ‘Done’).
8649 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
8650 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
8653 * // Example: Creating and opening a process dialog window.
8654 * function MyProcessDialog( config ) {
8655 * MyProcessDialog.parent.call( this, config );
8657 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
8659 * MyProcessDialog.static.title = 'Process dialog';
8660 * MyProcessDialog.static.actions = [
8661 * { action: 'save', label: 'Done', flags: 'primary' },
8662 * { label: 'Cancel', flags: 'safe' }
8665 * MyProcessDialog.prototype.initialize = function () {
8666 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
8667 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
8668 * 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>' );
8669 * this.$body.append( this.content.$element );
8671 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
8672 * var dialog = this;
8674 * return new OO.ui.Process( function () {
8675 * dialog.close( { action: action } );
8678 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
8681 * var windowManager = new OO.ui.WindowManager();
8682 * $( 'body' ).append( windowManager.$element );
8684 * var dialog = new MyProcessDialog();
8685 * windowManager.addWindows( [ dialog ] );
8686 * windowManager.openWindow( dialog );
8688 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
8692 * @extends OO.ui.Dialog
8695 * @param {Object} [config] Configuration options
8697 OO
.ui
.ProcessDialog
= function OoUiProcessDialog( config
) {
8698 // Parent constructor
8699 OO
.ui
.ProcessDialog
.parent
.call( this, config
);
8702 this.fitOnOpen
= false;
8705 this.$element
.addClass( 'oo-ui-processDialog' );
8710 OO
.inheritClass( OO
.ui
.ProcessDialog
, OO
.ui
.Dialog
);
8715 * Handle dismiss button click events.
8721 OO
.ui
.ProcessDialog
.prototype.onDismissErrorButtonClick = function () {
8726 * Handle retry button click events.
8728 * Hides errors and then tries again.
8732 OO
.ui
.ProcessDialog
.prototype.onRetryButtonClick = function () {
8734 this.executeAction( this.currentAction
);
8740 OO
.ui
.ProcessDialog
.prototype.onActionResize = function ( action
) {
8741 if ( this.actions
.isSpecial( action
) ) {
8744 return OO
.ui
.ProcessDialog
.parent
.prototype.onActionResize
.call( this, action
);
8750 OO
.ui
.ProcessDialog
.prototype.initialize = function () {
8752 OO
.ui
.ProcessDialog
.parent
.prototype.initialize
.call( this );
8755 this.$navigation
= $( '<div>' );
8756 this.$location
= $( '<div>' );
8757 this.$safeActions
= $( '<div>' );
8758 this.$primaryActions
= $( '<div>' );
8759 this.$otherActions
= $( '<div>' );
8760 this.dismissButton
= new OO
.ui
.ButtonWidget( {
8761 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' )
8763 this.retryButton
= new OO
.ui
.ButtonWidget();
8764 this.$errors
= $( '<div>' );
8765 this.$errorsTitle
= $( '<div>' );
8768 this.dismissButton
.connect( this, { click
: 'onDismissErrorButtonClick' } );
8769 this.retryButton
.connect( this, { click
: 'onRetryButtonClick' } );
8772 this.title
.$element
.addClass( 'oo-ui-processDialog-title' );
8774 .append( this.title
.$element
)
8775 .addClass( 'oo-ui-processDialog-location' );
8776 this.$safeActions
.addClass( 'oo-ui-processDialog-actions-safe' );
8777 this.$primaryActions
.addClass( 'oo-ui-processDialog-actions-primary' );
8778 this.$otherActions
.addClass( 'oo-ui-processDialog-actions-other' );
8780 .addClass( 'oo-ui-processDialog-errors-title' )
8781 .text( OO
.ui
.msg( 'ooui-dialog-process-error' ) );
8783 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
8784 .append( this.$errorsTitle
, this.dismissButton
.$element
, this.retryButton
.$element
);
8786 .addClass( 'oo-ui-processDialog-content' )
8787 .append( this.$errors
);
8789 .addClass( 'oo-ui-processDialog-navigation' )
8790 .append( this.$safeActions
, this.$location
, this.$primaryActions
);
8791 this.$head
.append( this.$navigation
);
8792 this.$foot
.append( this.$otherActions
);
8798 OO
.ui
.ProcessDialog
.prototype.getActionWidgets = function ( actions
) {
8799 var i
, len
, widgets
= [];
8800 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
8802 new OO
.ui
.ActionWidget( $.extend( { framed
: true }, actions
[ i
] ) )
8811 OO
.ui
.ProcessDialog
.prototype.attachActions = function () {
8812 var i
, len
, other
, special
, others
;
8815 OO
.ui
.ProcessDialog
.parent
.prototype.attachActions
.call( this );
8817 special
= this.actions
.getSpecial();
8818 others
= this.actions
.getOthers();
8819 if ( special
.primary
) {
8820 this.$primaryActions
.append( special
.primary
.$element
);
8822 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
8823 other
= others
[ i
];
8824 this.$otherActions
.append( other
.$element
);
8826 if ( special
.safe
) {
8827 this.$safeActions
.append( special
.safe
.$element
);
8831 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
8837 OO
.ui
.ProcessDialog
.prototype.executeAction = function ( action
) {
8839 return OO
.ui
.ProcessDialog
.parent
.prototype.executeAction
.call( this, action
)
8840 .fail( function ( errors
) {
8841 process
.showErrors( errors
|| [] );
8848 OO
.ui
.ProcessDialog
.prototype.setDimensions = function () {
8850 OO
.ui
.ProcessDialog
.parent
.prototype.setDimensions
.apply( this, arguments
);
8856 * Fit label between actions.
8861 OO
.ui
.ProcessDialog
.prototype.fitLabel = function () {
8862 var safeWidth
, primaryWidth
, biggerWidth
, labelWidth
, navigationWidth
, leftWidth
, rightWidth
,
8863 size
= this.getSizeProperties();
8865 if ( typeof size
.width
!== 'number' ) {
8866 if ( this.isOpened() ) {
8867 navigationWidth
= this.$head
.width() - 20;
8868 } else if ( this.isOpening() ) {
8869 if ( !this.fitOnOpen
) {
8870 // Size is relative and the dialog isn't open yet, so wait.
8871 this.manager
.opening
.done( this.fitLabel
.bind( this ) );
8872 this.fitOnOpen
= true;
8879 navigationWidth
= size
.width
- 20;
8882 safeWidth
= this.$safeActions
.is( ':visible' ) ? this.$safeActions
.width() : 0;
8883 primaryWidth
= this.$primaryActions
.is( ':visible' ) ? this.$primaryActions
.width() : 0;
8884 biggerWidth
= Math
.max( safeWidth
, primaryWidth
);
8886 labelWidth
= this.title
.$element
.width();
8888 if ( 2 * biggerWidth
+ labelWidth
< navigationWidth
) {
8889 // We have enough space to center the label
8890 leftWidth
= rightWidth
= biggerWidth
;
8892 // Let's hope we at least have enough space not to overlap, because we can't wrap the label…
8893 if ( this.getDir() === 'ltr' ) {
8894 leftWidth
= safeWidth
;
8895 rightWidth
= primaryWidth
;
8897 leftWidth
= primaryWidth
;
8898 rightWidth
= safeWidth
;
8902 this.$location
.css( { paddingLeft
: leftWidth
, paddingRight
: rightWidth
} );
8908 * Handle errors that occurred during accept or reject processes.
8911 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
8913 OO
.ui
.ProcessDialog
.prototype.showErrors = function ( errors
) {
8914 var i
, len
, $item
, actions
,
8920 if ( errors
instanceof OO
.ui
.Error
) {
8921 errors
= [ errors
];
8924 for ( i
= 0, len
= errors
.length
; i
< len
; i
++ ) {
8925 if ( !errors
[ i
].isRecoverable() ) {
8926 recoverable
= false;
8928 if ( errors
[ i
].isWarning() ) {
8931 $item
= $( '<div>' )
8932 .addClass( 'oo-ui-processDialog-error' )
8933 .append( errors
[ i
].getMessage() );
8934 items
.push( $item
[ 0 ] );
8936 this.$errorItems
= $( items
);
8937 if ( recoverable
) {
8938 abilities
[ this.currentAction
] = true;
8939 // Copy the flags from the first matching action
8940 actions
= this.actions
.get( { actions
: this.currentAction
} );
8941 if ( actions
.length
) {
8942 this.retryButton
.clearFlags().setFlags( actions
[ 0 ].getFlags() );
8945 abilities
[ this.currentAction
] = false;
8946 this.actions
.setAbilities( abilities
);
8949 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-continue' ) );
8951 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-retry' ) );
8953 this.retryButton
.toggle( recoverable
);
8954 this.$errorsTitle
.after( this.$errorItems
);
8955 this.$errors
.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
8963 OO
.ui
.ProcessDialog
.prototype.hideErrors = function () {
8964 this.$errors
.addClass( 'oo-ui-element-hidden' );
8965 if ( this.$errorItems
) {
8966 this.$errorItems
.remove();
8967 this.$errorItems
= null;
8974 OO
.ui
.ProcessDialog
.prototype.getTeardownProcess = function ( data
) {
8976 return OO
.ui
.ProcessDialog
.parent
.prototype.getTeardownProcess
.call( this, data
)
8977 .first( function () {
8978 // Make sure to hide errors
8980 this.fitOnOpen
= false;
8985 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
8986 * which is a widget that is specified by reference before any optional configuration settings.
8988 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
8990 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8991 * A left-alignment is used for forms with many fields.
8992 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8993 * A right-alignment is used for long but familiar forms which users tab through,
8994 * verifying the current field with a quick glance at the label.
8995 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8996 * that users fill out from top to bottom.
8997 * - **inline**: The label is placed after the field-widget and aligned to the left.
8998 * An inline-alignment is best used with checkboxes or radio buttons.
9000 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
9001 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
9003 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9005 * @extends OO.ui.Layout
9006 * @mixins OO.ui.mixin.LabelElement
9007 * @mixins OO.ui.mixin.TitledElement
9010 * @param {OO.ui.Widget} fieldWidget Field widget
9011 * @param {Object} [config] Configuration options
9012 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
9013 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
9014 * The array may contain strings or OO.ui.HtmlSnippet instances.
9015 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
9016 * The array may contain strings or OO.ui.HtmlSnippet instances.
9017 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
9018 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
9019 * For important messages, you are advised to use `notices`, as they are always shown.
9021 * @throws {Error} An error is thrown if no widget is specified
9023 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
9024 var hasInputWidget
, div
, i
;
9026 // Allow passing positional parameters inside the config object
9027 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
9028 config
= fieldWidget
;
9029 fieldWidget
= config
.fieldWidget
;
9032 // Make sure we have required constructor arguments
9033 if ( fieldWidget
=== undefined ) {
9034 throw new Error( 'Widget not found' );
9037 hasInputWidget
= fieldWidget
.constructor.static.supportsSimpleLabel
;
9039 // Configuration initialization
9040 config
= $.extend( { align
: 'left' }, config
);
9042 // Parent constructor
9043 OO
.ui
.FieldLayout
.parent
.call( this, config
);
9045 // Mixin constructors
9046 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9047 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
9050 this.fieldWidget
= fieldWidget
;
9051 this.errors
= config
.errors
|| [];
9052 this.notices
= config
.notices
|| [];
9053 this.$field
= $( '<div>' );
9054 this.$messages
= $( '<ul>' );
9055 this.$body
= $( '<' + ( hasInputWidget
? 'label' : 'div' ) + '>' );
9057 if ( config
.help
) {
9058 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
9059 classes
: [ 'oo-ui-fieldLayout-help' ],
9065 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
9066 div
.html( config
.help
.toString() );
9068 div
.text( config
.help
);
9070 this.popupButtonWidget
.getPopup().$body
.append(
9071 div
.addClass( 'oo-ui-fieldLayout-help-content' )
9073 this.$help
= this.popupButtonWidget
.$element
;
9075 this.$help
= $( [] );
9079 if ( hasInputWidget
) {
9080 this.$label
.on( 'click', this.onLabelClick
.bind( this ) );
9082 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
9086 .addClass( 'oo-ui-fieldLayout' )
9087 .append( this.$help
, this.$body
);
9088 if ( this.errors
.length
|| this.notices
.length
) {
9089 this.$element
.append( this.$messages
);
9091 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
9092 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
9094 .addClass( 'oo-ui-fieldLayout-field' )
9095 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget
.isDisabled() )
9096 .append( this.fieldWidget
.$element
);
9098 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
9099 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
9101 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
9102 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
9105 this.setAlignment( config
.align
);
9110 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
9111 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
9112 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
9117 * Handle field disable events.
9120 * @param {boolean} value Field is disabled
9122 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
9123 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
9127 * Handle label mouse click events.
9130 * @param {jQuery.Event} e Mouse click event
9132 OO
.ui
.FieldLayout
.prototype.onLabelClick = function () {
9133 this.fieldWidget
.simulateLabelClick();
9138 * Get the widget contained by the field.
9140 * @return {OO.ui.Widget} Field widget
9142 OO
.ui
.FieldLayout
.prototype.getField = function () {
9143 return this.fieldWidget
;
9147 * @param {string} kind 'error' or 'notice'
9148 * @param {string|OO.ui.HtmlSnippet} text
9151 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
9152 var $listItem
, $icon
, message
;
9153 $listItem
= $( '<li>' );
9154 if ( kind
=== 'error' ) {
9155 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
9156 } else if ( kind
=== 'notice' ) {
9157 $icon
= new OO
.ui
.IconWidget( { icon
: 'info' } ).$element
;
9161 message
= new OO
.ui
.LabelWidget( { label
: text
} );
9163 .append( $icon
, message
.$element
)
9164 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
9169 * Set the field alignment mode.
9172 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
9175 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
9176 if ( value
!== this.align
) {
9177 // Default to 'left'
9178 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
9182 if ( value
=== 'inline' ) {
9183 this.$body
.append( this.$field
, this.$label
);
9185 this.$body
.append( this.$label
, this.$field
);
9187 // Set classes. The following classes can be used here:
9188 // * oo-ui-fieldLayout-align-left
9189 // * oo-ui-fieldLayout-align-right
9190 // * oo-ui-fieldLayout-align-top
9191 // * oo-ui-fieldLayout-align-inline
9193 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
9195 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
9203 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
9204 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
9205 * is required and is specified before any optional configuration settings.
9207 * Labels can be aligned in one of four ways:
9209 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9210 * A left-alignment is used for forms with many fields.
9211 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9212 * A right-alignment is used for long but familiar forms which users tab through,
9213 * verifying the current field with a quick glance at the label.
9214 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9215 * that users fill out from top to bottom.
9216 * - **inline**: The label is placed after the field-widget and aligned to the left.
9217 * An inline-alignment is best used with checkboxes or radio buttons.
9219 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
9220 * text is specified.
9223 * // Example of an ActionFieldLayout
9224 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
9225 * new OO.ui.TextInputWidget( {
9226 * placeholder: 'Field widget'
9228 * new OO.ui.ButtonWidget( {
9232 * label: 'An ActionFieldLayout. This label is aligned top',
9234 * help: 'This is help text'
9238 * $( 'body' ).append( actionFieldLayout.$element );
9241 * @extends OO.ui.FieldLayout
9244 * @param {OO.ui.Widget} fieldWidget Field widget
9245 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
9247 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
9248 // Allow passing positional parameters inside the config object
9249 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
9250 config
= fieldWidget
;
9251 fieldWidget
= config
.fieldWidget
;
9252 buttonWidget
= config
.buttonWidget
;
9255 // Parent constructor
9256 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
9259 this.buttonWidget
= buttonWidget
;
9260 this.$button
= $( '<div>' );
9261 this.$input
= $( '<div>' );
9265 .addClass( 'oo-ui-actionFieldLayout' );
9267 .addClass( 'oo-ui-actionFieldLayout-button' )
9268 .append( this.buttonWidget
.$element
);
9270 .addClass( 'oo-ui-actionFieldLayout-input' )
9271 .append( this.fieldWidget
.$element
);
9273 .append( this.$input
, this.$button
);
9278 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
9281 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
9282 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
9283 * configured with a label as well. For more information and examples,
9284 * please see the [OOjs UI documentation on MediaWiki][1].
9287 * // Example of a fieldset layout
9288 * var input1 = new OO.ui.TextInputWidget( {
9289 * placeholder: 'A text input field'
9292 * var input2 = new OO.ui.TextInputWidget( {
9293 * placeholder: 'A text input field'
9296 * var fieldset = new OO.ui.FieldsetLayout( {
9297 * label: 'Example of a fieldset layout'
9300 * fieldset.addItems( [
9301 * new OO.ui.FieldLayout( input1, {
9302 * label: 'Field One'
9304 * new OO.ui.FieldLayout( input2, {
9305 * label: 'Field Two'
9308 * $( 'body' ).append( fieldset.$element );
9310 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9313 * @extends OO.ui.Layout
9314 * @mixins OO.ui.mixin.IconElement
9315 * @mixins OO.ui.mixin.LabelElement
9316 * @mixins OO.ui.mixin.GroupElement
9319 * @param {Object} [config] Configuration options
9320 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
9322 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
9323 // Configuration initialization
9324 config
= config
|| {};
9326 // Parent constructor
9327 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
9329 // Mixin constructors
9330 OO
.ui
.mixin
.IconElement
.call( this, config
);
9331 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9332 OO
.ui
.mixin
.GroupElement
.call( this, config
);
9334 if ( config
.help
) {
9335 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
9336 classes
: [ 'oo-ui-fieldsetLayout-help' ],
9341 this.popupButtonWidget
.getPopup().$body
.append(
9343 .text( config
.help
)
9344 .addClass( 'oo-ui-fieldsetLayout-help-content' )
9346 this.$help
= this.popupButtonWidget
.$element
;
9348 this.$help
= $( [] );
9353 .addClass( 'oo-ui-fieldsetLayout' )
9354 .prepend( this.$help
, this.$icon
, this.$label
, this.$group
);
9355 if ( Array
.isArray( config
.items
) ) {
9356 this.addItems( config
.items
);
9362 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
9363 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
9364 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
9365 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
9368 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
9369 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
9370 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
9371 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9373 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
9374 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
9375 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
9376 * some fancier controls. Some controls have both regular and InputWidget variants, for example
9377 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
9378 * often have simplified APIs to match the capabilities of HTML forms.
9379 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
9381 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
9382 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9385 * // Example of a form layout that wraps a fieldset layout
9386 * var input1 = new OO.ui.TextInputWidget( {
9387 * placeholder: 'Username'
9389 * var input2 = new OO.ui.TextInputWidget( {
9390 * placeholder: 'Password',
9393 * var submit = new OO.ui.ButtonInputWidget( {
9397 * var fieldset = new OO.ui.FieldsetLayout( {
9398 * label: 'A form layout'
9400 * fieldset.addItems( [
9401 * new OO.ui.FieldLayout( input1, {
9402 * label: 'Username',
9405 * new OO.ui.FieldLayout( input2, {
9406 * label: 'Password',
9409 * new OO.ui.FieldLayout( submit )
9411 * var form = new OO.ui.FormLayout( {
9412 * items: [ fieldset ],
9413 * action: '/api/formhandler',
9416 * $( 'body' ).append( form.$element );
9419 * @extends OO.ui.Layout
9420 * @mixins OO.ui.mixin.GroupElement
9423 * @param {Object} [config] Configuration options
9424 * @cfg {string} [method] HTML form `method` attribute
9425 * @cfg {string} [action] HTML form `action` attribute
9426 * @cfg {string} [enctype] HTML form `enctype` attribute
9427 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
9429 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
9430 // Configuration initialization
9431 config
= config
|| {};
9433 // Parent constructor
9434 OO
.ui
.FormLayout
.parent
.call( this, config
);
9436 // Mixin constructors
9437 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
9440 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
9442 // Make sure the action is safe
9443 if ( config
.action
!== undefined && !OO
.ui
.isSafeUrl( config
.action
) ) {
9444 throw new Error( 'Potentially unsafe action provided: ' + config
.action
);
9449 .addClass( 'oo-ui-formLayout' )
9451 method
: config
.method
,
9452 action
: config
.action
,
9453 enctype
: config
.enctype
9455 if ( Array
.isArray( config
.items
) ) {
9456 this.addItems( config
.items
);
9462 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
9463 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
9468 * A 'submit' event is emitted when the form is submitted.
9473 /* Static Properties */
9475 OO
.ui
.FormLayout
.static.tagName
= 'form';
9480 * Handle form submit events.
9483 * @param {jQuery.Event} e Submit event
9486 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
9487 if ( this.emit( 'submit' ) ) {
9493 * 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)
9494 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
9497 * var menuLayout = new OO.ui.MenuLayout( {
9500 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9501 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9502 * select = new OO.ui.SelectWidget( {
9504 * new OO.ui.OptionWidget( {
9508 * new OO.ui.OptionWidget( {
9512 * new OO.ui.OptionWidget( {
9516 * new OO.ui.OptionWidget( {
9521 * } ).on( 'select', function ( item ) {
9522 * menuLayout.setMenuPosition( item.getData() );
9525 * menuLayout.$menu.append(
9526 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
9528 * menuLayout.$content.append(
9529 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
9531 * $( 'body' ).append( menuLayout.$element );
9533 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
9534 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
9535 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
9538 * .oo-ui-menuLayout-menu {
9542 * .oo-ui-menuLayout-content {
9550 * @extends OO.ui.Layout
9553 * @param {Object} [config] Configuration options
9554 * @cfg {boolean} [showMenu=true] Show menu
9555 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
9557 OO
.ui
.MenuLayout
= function OoUiMenuLayout( config
) {
9558 // Configuration initialization
9559 config
= $.extend( {
9561 menuPosition
: 'before'
9564 // Parent constructor
9565 OO
.ui
.MenuLayout
.parent
.call( this, config
);
9570 * @property {jQuery}
9572 this.$menu
= $( '<div>' );
9576 * @property {jQuery}
9578 this.$content
= $( '<div>' );
9582 .addClass( 'oo-ui-menuLayout-menu' );
9583 this.$content
.addClass( 'oo-ui-menuLayout-content' );
9585 .addClass( 'oo-ui-menuLayout' )
9586 .append( this.$content
, this.$menu
);
9587 this.setMenuPosition( config
.menuPosition
);
9588 this.toggleMenu( config
.showMenu
);
9593 OO
.inheritClass( OO
.ui
.MenuLayout
, OO
.ui
.Layout
);
9600 * @param {boolean} showMenu Show menu, omit to toggle
9603 OO
.ui
.MenuLayout
.prototype.toggleMenu = function ( showMenu
) {
9604 showMenu
= showMenu
=== undefined ? !this.showMenu
: !!showMenu
;
9606 if ( this.showMenu
!== showMenu
) {
9607 this.showMenu
= showMenu
;
9609 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu
)
9610 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu
);
9617 * Check if menu is visible
9619 * @return {boolean} Menu is visible
9621 OO
.ui
.MenuLayout
.prototype.isMenuVisible = function () {
9622 return this.showMenu
;
9626 * Set menu position.
9628 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
9629 * @throws {Error} If position value is not supported
9632 OO
.ui
.MenuLayout
.prototype.setMenuPosition = function ( position
) {
9633 this.$element
.removeClass( 'oo-ui-menuLayout-' + this.menuPosition
);
9634 this.menuPosition
= position
;
9635 this.$element
.addClass( 'oo-ui-menuLayout-' + position
);
9641 * Get menu position.
9643 * @return {string} Menu position
9645 OO
.ui
.MenuLayout
.prototype.getMenuPosition = function () {
9646 return this.menuPosition
;
9650 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
9651 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
9652 * through the pages and select which one to display. By default, only one page is
9653 * displayed at a time and the outline is hidden. When a user navigates to a new page,
9654 * the booklet layout automatically focuses on the first focusable element, unless the
9655 * default setting is changed. Optionally, booklets can be configured to show
9656 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
9659 * // Example of a BookletLayout that contains two PageLayouts.
9661 * function PageOneLayout( name, config ) {
9662 * PageOneLayout.parent.call( this, name, config );
9663 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
9665 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
9666 * PageOneLayout.prototype.setupOutlineItem = function () {
9667 * this.outlineItem.setLabel( 'Page One' );
9670 * function PageTwoLayout( name, config ) {
9671 * PageTwoLayout.parent.call( this, name, config );
9672 * this.$element.append( '<p>Second page</p>' );
9674 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
9675 * PageTwoLayout.prototype.setupOutlineItem = function () {
9676 * this.outlineItem.setLabel( 'Page Two' );
9679 * var page1 = new PageOneLayout( 'one' ),
9680 * page2 = new PageTwoLayout( 'two' );
9682 * var booklet = new OO.ui.BookletLayout( {
9686 * booklet.addPages ( [ page1, page2 ] );
9687 * $( 'body' ).append( booklet.$element );
9690 * @extends OO.ui.MenuLayout
9693 * @param {Object} [config] Configuration options
9694 * @cfg {boolean} [continuous=false] Show all pages, one after another
9695 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
9696 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
9697 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
9699 OO
.ui
.BookletLayout
= function OoUiBookletLayout( config
) {
9700 // Configuration initialization
9701 config
= config
|| {};
9703 // Parent constructor
9704 OO
.ui
.BookletLayout
.parent
.call( this, config
);
9707 this.currentPageName
= null;
9709 this.ignoreFocus
= false;
9710 this.stackLayout
= new OO
.ui
.StackLayout( { continuous
: !!config
.continuous
} );
9711 this.$content
.append( this.stackLayout
.$element
);
9712 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
9713 this.outlineVisible
= false;
9714 this.outlined
= !!config
.outlined
;
9715 if ( this.outlined
) {
9716 this.editable
= !!config
.editable
;
9717 this.outlineControlsWidget
= null;
9718 this.outlineSelectWidget
= new OO
.ui
.OutlineSelectWidget();
9719 this.outlinePanel
= new OO
.ui
.PanelLayout( { scrollable
: true } );
9720 this.$menu
.append( this.outlinePanel
.$element
);
9721 this.outlineVisible
= true;
9722 if ( this.editable
) {
9723 this.outlineControlsWidget
= new OO
.ui
.OutlineControlsWidget(
9724 this.outlineSelectWidget
9728 this.toggleMenu( this.outlined
);
9731 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
9732 if ( this.outlined
) {
9733 this.outlineSelectWidget
.connect( this, { select
: 'onOutlineSelectWidgetSelect' } );
9734 this.scrolling
= false;
9735 this.stackLayout
.connect( this, { visibleItemChange
: 'onStackLayoutVisibleItemChange' } );
9737 if ( this.autoFocus
) {
9738 // Event 'focus' does not bubble, but 'focusin' does
9739 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
9743 this.$element
.addClass( 'oo-ui-bookletLayout' );
9744 this.stackLayout
.$element
.addClass( 'oo-ui-bookletLayout-stackLayout' );
9745 if ( this.outlined
) {
9746 this.outlinePanel
.$element
9747 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
9748 .append( this.outlineSelectWidget
.$element
);
9749 if ( this.editable
) {
9750 this.outlinePanel
.$element
9751 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
9752 .append( this.outlineControlsWidget
.$element
);
9759 OO
.inheritClass( OO
.ui
.BookletLayout
, OO
.ui
.MenuLayout
);
9764 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
9766 * @param {OO.ui.PageLayout} page Current page
9770 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
9773 * @param {OO.ui.PageLayout[]} page Added pages
9774 * @param {number} index Index pages were added at
9778 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
9779 * {@link #removePages removed} from the booklet.
9782 * @param {OO.ui.PageLayout[]} pages Removed pages
9788 * Handle stack layout focus.
9791 * @param {jQuery.Event} e Focusin event
9793 OO
.ui
.BookletLayout
.prototype.onStackLayoutFocus = function ( e
) {
9796 // Find the page that an element was focused within
9797 $target
= $( e
.target
).closest( '.oo-ui-pageLayout' );
9798 for ( name
in this.pages
) {
9799 // Check for page match, exclude current page to find only page changes
9800 if ( this.pages
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentPageName
) {
9801 this.setPage( name
);
9808 * Handle visibleItemChange events from the stackLayout
9810 * The next visible page is set as the current page by selecting it
9813 * @param {OO.ui.PageLayout} page The next visible page in the layout
9815 OO
.ui
.BookletLayout
.prototype.onStackLayoutVisibleItemChange = function ( page
) {
9816 // Set a flag to so that the resulting call to #onStackLayoutSet doesn't
9817 // try and scroll the item into view again.
9818 this.scrolling
= true;
9819 this.outlineSelectWidget
.selectItemByData( page
.getName() );
9820 this.scrolling
= false;
9824 * Handle stack layout set events.
9827 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
9829 OO
.ui
.BookletLayout
.prototype.onStackLayoutSet = function ( page
) {
9831 if ( !this.scrolling
&& page
) {
9832 page
.scrollElementIntoView( { complete: function () {
9833 if ( layout
.autoFocus
) {
9841 * Focus the first input in the current page.
9843 * If no page is selected, the first selectable page will be selected.
9844 * If the focus is already in an element on the current page, nothing will happen.
9845 * @param {number} [itemIndex] A specific item to focus on
9847 OO
.ui
.BookletLayout
.prototype.focus = function ( itemIndex
) {
9849 items
= this.stackLayout
.getItems();
9851 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
9852 page
= items
[ itemIndex
];
9854 page
= this.stackLayout
.getCurrentItem();
9857 if ( !page
&& this.outlined
) {
9858 this.selectFirstSelectablePage();
9859 page
= this.stackLayout
.getCurrentItem();
9864 // Only change the focus if is not already in the current page
9865 if ( !OO
.ui
.contains( page
.$element
[ 0 ], this.getElementDocument().activeElement
, true ) ) {
9871 * Find the first focusable input in the booklet layout and focus
9874 OO
.ui
.BookletLayout
.prototype.focusFirstFocusable = function () {
9875 OO
.ui
.findFocusable( this.stackLayout
.$element
).focus();
9879 * Handle outline widget select events.
9882 * @param {OO.ui.OptionWidget|null} item Selected item
9884 OO
.ui
.BookletLayout
.prototype.onOutlineSelectWidgetSelect = function ( item
) {
9886 this.setPage( item
.getData() );
9891 * Check if booklet has an outline.
9893 * @return {boolean} Booklet has an outline
9895 OO
.ui
.BookletLayout
.prototype.isOutlined = function () {
9896 return this.outlined
;
9900 * Check if booklet has editing controls.
9902 * @return {boolean} Booklet is editable
9904 OO
.ui
.BookletLayout
.prototype.isEditable = function () {
9905 return this.editable
;
9909 * Check if booklet has a visible outline.
9911 * @return {boolean} Outline is visible
9913 OO
.ui
.BookletLayout
.prototype.isOutlineVisible = function () {
9914 return this.outlined
&& this.outlineVisible
;
9918 * Hide or show the outline.
9920 * @param {boolean} [show] Show outline, omit to invert current state
9923 OO
.ui
.BookletLayout
.prototype.toggleOutline = function ( show
) {
9924 if ( this.outlined
) {
9925 show
= show
=== undefined ? !this.outlineVisible
: !!show
;
9926 this.outlineVisible
= show
;
9927 this.toggleMenu( show
);
9934 * Get the page closest to the specified page.
9936 * @param {OO.ui.PageLayout} page Page to use as a reference point
9937 * @return {OO.ui.PageLayout|null} Page closest to the specified page
9939 OO
.ui
.BookletLayout
.prototype.getClosestPage = function ( page
) {
9940 var next
, prev
, level
,
9941 pages
= this.stackLayout
.getItems(),
9942 index
= pages
.indexOf( page
);
9944 if ( index
!== -1 ) {
9945 next
= pages
[ index
+ 1 ];
9946 prev
= pages
[ index
- 1 ];
9947 // Prefer adjacent pages at the same level
9948 if ( this.outlined
) {
9949 level
= this.outlineSelectWidget
.getItemFromData( page
.getName() ).getLevel();
9952 level
=== this.outlineSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
9958 level
=== this.outlineSelectWidget
.getItemFromData( next
.getName() ).getLevel()
9964 return prev
|| next
|| null;
9968 * Get the outline widget.
9970 * If the booklet is not outlined, the method will return `null`.
9972 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
9974 OO
.ui
.BookletLayout
.prototype.getOutline = function () {
9975 return this.outlineSelectWidget
;
9979 * Get the outline controls widget.
9981 * If the outline is not editable, the method will return `null`.
9983 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
9985 OO
.ui
.BookletLayout
.prototype.getOutlineControls = function () {
9986 return this.outlineControlsWidget
;
9990 * Get a page by its symbolic name.
9992 * @param {string} name Symbolic name of page
9993 * @return {OO.ui.PageLayout|undefined} Page, if found
9995 OO
.ui
.BookletLayout
.prototype.getPage = function ( name
) {
9996 return this.pages
[ name
];
10000 * Get the current page.
10002 * @return {OO.ui.PageLayout|undefined} Current page, if found
10004 OO
.ui
.BookletLayout
.prototype.getCurrentPage = function () {
10005 var name
= this.getCurrentPageName();
10006 return name
? this.getPage( name
) : undefined;
10010 * Get the symbolic name of the current page.
10012 * @return {string|null} Symbolic name of the current page
10014 OO
.ui
.BookletLayout
.prototype.getCurrentPageName = function () {
10015 return this.currentPageName
;
10019 * Add pages to the booklet layout
10021 * When pages are added with the same names as existing pages, the existing pages will be
10022 * automatically removed before the new pages are added.
10024 * @param {OO.ui.PageLayout[]} pages Pages to add
10025 * @param {number} index Index of the insertion point
10029 OO
.ui
.BookletLayout
.prototype.addPages = function ( pages
, index
) {
10030 var i
, len
, name
, page
, item
, currentIndex
,
10031 stackLayoutPages
= this.stackLayout
.getItems(),
10035 // Remove pages with same names
10036 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
10038 name
= page
.getName();
10040 if ( Object
.prototype.hasOwnProperty
.call( this.pages
, name
) ) {
10041 // Correct the insertion index
10042 currentIndex
= stackLayoutPages
.indexOf( this.pages
[ name
] );
10043 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
10046 remove
.push( this.pages
[ name
] );
10049 if ( remove
.length
) {
10050 this.removePages( remove
);
10054 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
10056 name
= page
.getName();
10057 this.pages
[ page
.getName() ] = page
;
10058 if ( this.outlined
) {
10059 item
= new OO
.ui
.OutlineOptionWidget( { data
: name
} );
10060 page
.setOutlineItem( item
);
10061 items
.push( item
);
10065 if ( this.outlined
&& items
.length
) {
10066 this.outlineSelectWidget
.addItems( items
, index
);
10067 this.selectFirstSelectablePage();
10069 this.stackLayout
.addItems( pages
, index
);
10070 this.emit( 'add', pages
, index
);
10076 * Remove the specified pages from the booklet layout.
10078 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
10080 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
10084 OO
.ui
.BookletLayout
.prototype.removePages = function ( pages
) {
10085 var i
, len
, name
, page
,
10088 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
10090 name
= page
.getName();
10091 delete this.pages
[ name
];
10092 if ( this.outlined
) {
10093 items
.push( this.outlineSelectWidget
.getItemFromData( name
) );
10094 page
.setOutlineItem( null );
10097 if ( this.outlined
&& items
.length
) {
10098 this.outlineSelectWidget
.removeItems( items
);
10099 this.selectFirstSelectablePage();
10101 this.stackLayout
.removeItems( pages
);
10102 this.emit( 'remove', pages
);
10108 * Clear all pages from the booklet layout.
10110 * To remove only a subset of pages from the booklet, use the #removePages method.
10115 OO
.ui
.BookletLayout
.prototype.clearPages = function () {
10117 pages
= this.stackLayout
.getItems();
10120 this.currentPageName
= null;
10121 if ( this.outlined
) {
10122 this.outlineSelectWidget
.clearItems();
10123 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
10124 pages
[ i
].setOutlineItem( null );
10127 this.stackLayout
.clearItems();
10129 this.emit( 'remove', pages
);
10135 * Set the current page by symbolic name.
10138 * @param {string} name Symbolic name of page
10140 OO
.ui
.BookletLayout
.prototype.setPage = function ( name
) {
10143 page
= this.pages
[ name
],
10144 previousPage
= this.currentPageName
&& this.pages
[ this.currentPageName
];
10146 if ( name
!== this.currentPageName
) {
10147 if ( this.outlined
) {
10148 selectedItem
= this.outlineSelectWidget
.getSelectedItem();
10149 if ( selectedItem
&& selectedItem
.getData() !== name
) {
10150 this.outlineSelectWidget
.selectItemByData( name
);
10154 if ( previousPage
) {
10155 previousPage
.setActive( false );
10156 // Blur anything focused if the next page doesn't have anything focusable.
10157 // This is not needed if the next page has something focusable (because once it is focused
10158 // this blur happens automatically). If the layout is non-continuous, this check is
10159 // meaningless because the next page is not visible yet and thus can't hold focus.
10162 this.stackLayout
.continuous
&&
10163 OO
.ui
.findFocusable( page
.$element
).length
!== 0
10165 $focused
= previousPage
.$element
.find( ':focus' );
10166 if ( $focused
.length
) {
10167 $focused
[ 0 ].blur();
10171 this.currentPageName
= name
;
10172 page
.setActive( true );
10173 this.stackLayout
.setItem( page
);
10174 if ( !this.stackLayout
.continuous
&& previousPage
) {
10175 // This should not be necessary, since any inputs on the previous page should have been
10176 // blurred when it was hidden, but browsers are not very consistent about this.
10177 $focused
= previousPage
.$element
.find( ':focus' );
10178 if ( $focused
.length
) {
10179 $focused
[ 0 ].blur();
10182 this.emit( 'set', page
);
10188 * Select the first selectable page.
10192 OO
.ui
.BookletLayout
.prototype.selectFirstSelectablePage = function () {
10193 if ( !this.outlineSelectWidget
.getSelectedItem() ) {
10194 this.outlineSelectWidget
.selectItem( this.outlineSelectWidget
.getFirstSelectableItem() );
10201 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
10202 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
10203 * select which one to display. By default, only one card is displayed at a time. When a user
10204 * navigates to a new card, the index layout automatically focuses on the first focusable element,
10205 * unless the default setting is changed.
10207 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
10210 * // Example of a IndexLayout that contains two CardLayouts.
10212 * function CardOneLayout( name, config ) {
10213 * CardOneLayout.parent.call( this, name, config );
10214 * this.$element.append( '<p>First card</p>' );
10216 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
10217 * CardOneLayout.prototype.setupTabItem = function () {
10218 * this.tabItem.setLabel( 'Card one' );
10221 * var card1 = new CardOneLayout( 'one' ),
10222 * card2 = new CardLayout( 'two', { label: 'Card two' } );
10224 * card2.$element.append( '<p>Second card</p>' );
10226 * var index = new OO.ui.IndexLayout();
10228 * index.addCards ( [ card1, card2 ] );
10229 * $( 'body' ).append( index.$element );
10232 * @extends OO.ui.MenuLayout
10235 * @param {Object} [config] Configuration options
10236 * @cfg {boolean} [continuous=false] Show all cards, one after another
10237 * @cfg {boolean} [expanded=true] Expand the content panel to fill the entire parent element.
10238 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
10240 OO
.ui
.IndexLayout
= function OoUiIndexLayout( config
) {
10241 // Configuration initialization
10242 config
= $.extend( {}, config
, { menuPosition
: 'top' } );
10244 // Parent constructor
10245 OO
.ui
.IndexLayout
.parent
.call( this, config
);
10248 this.currentCardName
= null;
10250 this.ignoreFocus
= false;
10251 this.stackLayout
= new OO
.ui
.StackLayout( {
10252 continuous
: !!config
.continuous
,
10253 expanded
: config
.expanded
10255 this.$content
.append( this.stackLayout
.$element
);
10256 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
10258 this.tabSelectWidget
= new OO
.ui
.TabSelectWidget();
10259 this.tabPanel
= new OO
.ui
.PanelLayout();
10260 this.$menu
.append( this.tabPanel
.$element
);
10262 this.toggleMenu( true );
10265 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
10266 this.tabSelectWidget
.connect( this, { select
: 'onTabSelectWidgetSelect' } );
10267 if ( this.autoFocus
) {
10268 // Event 'focus' does not bubble, but 'focusin' does
10269 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
10273 this.$element
.addClass( 'oo-ui-indexLayout' );
10274 this.stackLayout
.$element
.addClass( 'oo-ui-indexLayout-stackLayout' );
10275 this.tabPanel
.$element
10276 .addClass( 'oo-ui-indexLayout-tabPanel' )
10277 .append( this.tabSelectWidget
.$element
);
10282 OO
.inheritClass( OO
.ui
.IndexLayout
, OO
.ui
.MenuLayout
);
10287 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
10289 * @param {OO.ui.CardLayout} card Current card
10293 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
10296 * @param {OO.ui.CardLayout[]} card Added cards
10297 * @param {number} index Index cards were added at
10301 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
10302 * {@link #removeCards removed} from the index.
10305 * @param {OO.ui.CardLayout[]} cards Removed cards
10311 * Handle stack layout focus.
10314 * @param {jQuery.Event} e Focusin event
10316 OO
.ui
.IndexLayout
.prototype.onStackLayoutFocus = function ( e
) {
10319 // Find the card that an element was focused within
10320 $target
= $( e
.target
).closest( '.oo-ui-cardLayout' );
10321 for ( name
in this.cards
) {
10322 // Check for card match, exclude current card to find only card changes
10323 if ( this.cards
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentCardName
) {
10324 this.setCard( name
);
10331 * Handle stack layout set events.
10334 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
10336 OO
.ui
.IndexLayout
.prototype.onStackLayoutSet = function ( card
) {
10339 card
.scrollElementIntoView( { complete: function () {
10340 if ( layout
.autoFocus
) {
10348 * Focus the first input in the current card.
10350 * If no card is selected, the first selectable card will be selected.
10351 * If the focus is already in an element on the current card, nothing will happen.
10352 * @param {number} [itemIndex] A specific item to focus on
10354 OO
.ui
.IndexLayout
.prototype.focus = function ( itemIndex
) {
10356 items
= this.stackLayout
.getItems();
10358 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
10359 card
= items
[ itemIndex
];
10361 card
= this.stackLayout
.getCurrentItem();
10365 this.selectFirstSelectableCard();
10366 card
= this.stackLayout
.getCurrentItem();
10371 // Only change the focus if is not already in the current page
10372 if ( !OO
.ui
.contains( card
.$element
[ 0 ], this.getElementDocument().activeElement
, true ) ) {
10378 * Find the first focusable input in the index layout and focus
10381 OO
.ui
.IndexLayout
.prototype.focusFirstFocusable = function () {
10382 OO
.ui
.findFocusable( this.stackLayout
.$element
).focus();
10386 * Handle tab widget select events.
10389 * @param {OO.ui.OptionWidget|null} item Selected item
10391 OO
.ui
.IndexLayout
.prototype.onTabSelectWidgetSelect = function ( item
) {
10393 this.setCard( item
.getData() );
10398 * Get the card closest to the specified card.
10400 * @param {OO.ui.CardLayout} card Card to use as a reference point
10401 * @return {OO.ui.CardLayout|null} Card closest to the specified card
10403 OO
.ui
.IndexLayout
.prototype.getClosestCard = function ( card
) {
10404 var next
, prev
, level
,
10405 cards
= this.stackLayout
.getItems(),
10406 index
= cards
.indexOf( card
);
10408 if ( index
!== -1 ) {
10409 next
= cards
[ index
+ 1 ];
10410 prev
= cards
[ index
- 1 ];
10411 // Prefer adjacent cards at the same level
10412 level
= this.tabSelectWidget
.getItemFromData( card
.getName() ).getLevel();
10415 level
=== this.tabSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
10421 level
=== this.tabSelectWidget
.getItemFromData( next
.getName() ).getLevel()
10426 return prev
|| next
|| null;
10430 * Get the tabs widget.
10432 * @return {OO.ui.TabSelectWidget} Tabs widget
10434 OO
.ui
.IndexLayout
.prototype.getTabs = function () {
10435 return this.tabSelectWidget
;
10439 * Get a card by its symbolic name.
10441 * @param {string} name Symbolic name of card
10442 * @return {OO.ui.CardLayout|undefined} Card, if found
10444 OO
.ui
.IndexLayout
.prototype.getCard = function ( name
) {
10445 return this.cards
[ name
];
10449 * Get the current card.
10451 * @return {OO.ui.CardLayout|undefined} Current card, if found
10453 OO
.ui
.IndexLayout
.prototype.getCurrentCard = function () {
10454 var name
= this.getCurrentCardName();
10455 return name
? this.getCard( name
) : undefined;
10459 * Get the symbolic name of the current card.
10461 * @return {string|null} Symbolic name of the current card
10463 OO
.ui
.IndexLayout
.prototype.getCurrentCardName = function () {
10464 return this.currentCardName
;
10468 * Add cards to the index layout
10470 * When cards are added with the same names as existing cards, the existing cards will be
10471 * automatically removed before the new cards are added.
10473 * @param {OO.ui.CardLayout[]} cards Cards to add
10474 * @param {number} index Index of the insertion point
10478 OO
.ui
.IndexLayout
.prototype.addCards = function ( cards
, index
) {
10479 var i
, len
, name
, card
, item
, currentIndex
,
10480 stackLayoutCards
= this.stackLayout
.getItems(),
10484 // Remove cards with same names
10485 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10487 name
= card
.getName();
10489 if ( Object
.prototype.hasOwnProperty
.call( this.cards
, name
) ) {
10490 // Correct the insertion index
10491 currentIndex
= stackLayoutCards
.indexOf( this.cards
[ name
] );
10492 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
10495 remove
.push( this.cards
[ name
] );
10498 if ( remove
.length
) {
10499 this.removeCards( remove
);
10503 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10505 name
= card
.getName();
10506 this.cards
[ card
.getName() ] = card
;
10507 item
= new OO
.ui
.TabOptionWidget( { data
: name
} );
10508 card
.setTabItem( item
);
10509 items
.push( item
);
10512 if ( items
.length
) {
10513 this.tabSelectWidget
.addItems( items
, index
);
10514 this.selectFirstSelectableCard();
10516 this.stackLayout
.addItems( cards
, index
);
10517 this.emit( 'add', cards
, index
);
10523 * Remove the specified cards from the index layout.
10525 * To remove all cards from the index, you may wish to use the #clearCards method instead.
10527 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
10531 OO
.ui
.IndexLayout
.prototype.removeCards = function ( cards
) {
10532 var i
, len
, name
, card
,
10535 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10537 name
= card
.getName();
10538 delete this.cards
[ name
];
10539 items
.push( this.tabSelectWidget
.getItemFromData( name
) );
10540 card
.setTabItem( null );
10542 if ( items
.length
) {
10543 this.tabSelectWidget
.removeItems( items
);
10544 this.selectFirstSelectableCard();
10546 this.stackLayout
.removeItems( cards
);
10547 this.emit( 'remove', cards
);
10553 * Clear all cards from the index layout.
10555 * To remove only a subset of cards from the index, use the #removeCards method.
10560 OO
.ui
.IndexLayout
.prototype.clearCards = function () {
10562 cards
= this.stackLayout
.getItems();
10565 this.currentCardName
= null;
10566 this.tabSelectWidget
.clearItems();
10567 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10568 cards
[ i
].setTabItem( null );
10570 this.stackLayout
.clearItems();
10572 this.emit( 'remove', cards
);
10578 * Set the current card by symbolic name.
10581 * @param {string} name Symbolic name of card
10583 OO
.ui
.IndexLayout
.prototype.setCard = function ( name
) {
10586 card
= this.cards
[ name
],
10587 previousCard
= this.currentCardName
&& this.cards
[ this.currentCardName
];
10589 if ( name
!== this.currentCardName
) {
10590 selectedItem
= this.tabSelectWidget
.getSelectedItem();
10591 if ( selectedItem
&& selectedItem
.getData() !== name
) {
10592 this.tabSelectWidget
.selectItemByData( name
);
10595 if ( previousCard
) {
10596 previousCard
.setActive( false );
10597 // Blur anything focused if the next card doesn't have anything focusable.
10598 // This is not needed if the next card has something focusable (because once it is focused
10599 // this blur happens automatically). If the layout is non-continuous, this check is
10600 // meaningless because the next card is not visible yet and thus can't hold focus.
10603 this.stackLayout
.continuous
&&
10604 OO
.ui
.findFocusable( card
.$element
).length
!== 0
10606 $focused
= previousCard
.$element
.find( ':focus' );
10607 if ( $focused
.length
) {
10608 $focused
[ 0 ].blur();
10612 this.currentCardName
= name
;
10613 card
.setActive( true );
10614 this.stackLayout
.setItem( card
);
10615 if ( !this.stackLayout
.continuous
&& previousCard
) {
10616 // This should not be necessary, since any inputs on the previous card should have been
10617 // blurred when it was hidden, but browsers are not very consistent about this.
10618 $focused
= previousCard
.$element
.find( ':focus' );
10619 if ( $focused
.length
) {
10620 $focused
[ 0 ].blur();
10623 this.emit( 'set', card
);
10629 * Select the first selectable card.
10633 OO
.ui
.IndexLayout
.prototype.selectFirstSelectableCard = function () {
10634 if ( !this.tabSelectWidget
.getSelectedItem() ) {
10635 this.tabSelectWidget
.selectItem( this.tabSelectWidget
.getFirstSelectableItem() );
10642 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10643 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10646 * // Example of a panel layout
10647 * var panel = new OO.ui.PanelLayout( {
10651 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10653 * $( 'body' ).append( panel.$element );
10656 * @extends OO.ui.Layout
10659 * @param {Object} [config] Configuration options
10660 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10661 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10662 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10663 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10665 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
10666 // Configuration initialization
10667 config
= $.extend( {
10674 // Parent constructor
10675 OO
.ui
.PanelLayout
.parent
.call( this, config
);
10678 this.$element
.addClass( 'oo-ui-panelLayout' );
10679 if ( config
.scrollable
) {
10680 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
10682 if ( config
.padded
) {
10683 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
10685 if ( config
.expanded
) {
10686 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
10688 if ( config
.framed
) {
10689 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
10695 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
10700 * Focus the panel layout
10702 * The default implementation just focuses the first focusable element in the panel
10704 OO
.ui
.PanelLayout
.prototype.focus = function () {
10705 OO
.ui
.findFocusable( this.$element
).focus();
10709 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
10710 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
10711 * rather extended to include the required content and functionality.
10713 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
10714 * item is customized (with a label) using the #setupTabItem method. See
10715 * {@link OO.ui.IndexLayout IndexLayout} for an example.
10718 * @extends OO.ui.PanelLayout
10721 * @param {string} name Unique symbolic name of card
10722 * @param {Object} [config] Configuration options
10723 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] Label for card's tab
10725 OO
.ui
.CardLayout
= function OoUiCardLayout( name
, config
) {
10726 // Allow passing positional parameters inside the config object
10727 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
10729 name
= config
.name
;
10732 // Configuration initialization
10733 config
= $.extend( { scrollable
: true }, config
);
10735 // Parent constructor
10736 OO
.ui
.CardLayout
.parent
.call( this, config
);
10740 this.label
= config
.label
;
10741 this.tabItem
= null;
10742 this.active
= false;
10745 this.$element
.addClass( 'oo-ui-cardLayout' );
10750 OO
.inheritClass( OO
.ui
.CardLayout
, OO
.ui
.PanelLayout
);
10755 * An 'active' event is emitted when the card becomes active. Cards become active when they are
10756 * shown in a index layout that is configured to display only one card at a time.
10759 * @param {boolean} active Card is active
10765 * Get the symbolic name of the card.
10767 * @return {string} Symbolic name of card
10769 OO
.ui
.CardLayout
.prototype.getName = function () {
10774 * Check if card is active.
10776 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
10777 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
10779 * @return {boolean} Card is active
10781 OO
.ui
.CardLayout
.prototype.isActive = function () {
10782 return this.active
;
10788 * The tab item allows users to access the card from the index's tab
10789 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
10791 * @return {OO.ui.TabOptionWidget|null} Tab option widget
10793 OO
.ui
.CardLayout
.prototype.getTabItem = function () {
10794 return this.tabItem
;
10798 * Set or unset the tab item.
10800 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
10801 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
10802 * level), use #setupTabItem instead of this method.
10804 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
10807 OO
.ui
.CardLayout
.prototype.setTabItem = function ( tabItem
) {
10808 this.tabItem
= tabItem
|| null;
10810 this.setupTabItem();
10816 * Set up the tab item.
10818 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
10819 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
10820 * the #setTabItem method instead.
10822 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
10825 OO
.ui
.CardLayout
.prototype.setupTabItem = function () {
10826 if ( this.label
) {
10827 this.tabItem
.setLabel( this.label
);
10833 * Set the card to its 'active' state.
10835 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
10836 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
10837 * context, setting the active state on a card does nothing.
10839 * @param {boolean} value Card is active
10842 OO
.ui
.CardLayout
.prototype.setActive = function ( active
) {
10845 if ( active
!== this.active
) {
10846 this.active
= active
;
10847 this.$element
.toggleClass( 'oo-ui-cardLayout-active', this.active
);
10848 this.emit( 'active', this.active
);
10853 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
10854 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
10855 * rather extended to include the required content and functionality.
10857 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
10858 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
10859 * {@link OO.ui.BookletLayout BookletLayout} for an example.
10862 * @extends OO.ui.PanelLayout
10865 * @param {string} name Unique symbolic name of page
10866 * @param {Object} [config] Configuration options
10868 OO
.ui
.PageLayout
= function OoUiPageLayout( name
, config
) {
10869 // Allow passing positional parameters inside the config object
10870 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
10872 name
= config
.name
;
10875 // Configuration initialization
10876 config
= $.extend( { scrollable
: true }, config
);
10878 // Parent constructor
10879 OO
.ui
.PageLayout
.parent
.call( this, config
);
10883 this.outlineItem
= null;
10884 this.active
= false;
10887 this.$element
.addClass( 'oo-ui-pageLayout' );
10892 OO
.inheritClass( OO
.ui
.PageLayout
, OO
.ui
.PanelLayout
);
10897 * An 'active' event is emitted when the page becomes active. Pages become active when they are
10898 * shown in a booklet layout that is configured to display only one page at a time.
10901 * @param {boolean} active Page is active
10907 * Get the symbolic name of the page.
10909 * @return {string} Symbolic name of page
10911 OO
.ui
.PageLayout
.prototype.getName = function () {
10916 * Check if page is active.
10918 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
10919 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
10921 * @return {boolean} Page is active
10923 OO
.ui
.PageLayout
.prototype.isActive = function () {
10924 return this.active
;
10928 * Get outline item.
10930 * The outline item allows users to access the page from the booklet's outline
10931 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
10933 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
10935 OO
.ui
.PageLayout
.prototype.getOutlineItem = function () {
10936 return this.outlineItem
;
10940 * Set or unset the outline item.
10942 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
10943 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
10944 * level), use #setupOutlineItem instead of this method.
10946 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
10949 OO
.ui
.PageLayout
.prototype.setOutlineItem = function ( outlineItem
) {
10950 this.outlineItem
= outlineItem
|| null;
10951 if ( outlineItem
) {
10952 this.setupOutlineItem();
10958 * Set up the outline item.
10960 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
10961 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
10962 * the #setOutlineItem method instead.
10964 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
10967 OO
.ui
.PageLayout
.prototype.setupOutlineItem = function () {
10972 * Set the page to its 'active' state.
10974 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
10975 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
10976 * context, setting the active state on a page does nothing.
10978 * @param {boolean} value Page is active
10981 OO
.ui
.PageLayout
.prototype.setActive = function ( active
) {
10984 if ( active
!== this.active
) {
10985 this.active
= active
;
10986 this.$element
.toggleClass( 'oo-ui-pageLayout-active', active
);
10987 this.emit( 'active', this.active
);
10992 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
10993 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
10994 * by setting the #continuous option to 'true'.
10997 * // A stack layout with two panels, configured to be displayed continously
10998 * var myStack = new OO.ui.StackLayout( {
11000 * new OO.ui.PanelLayout( {
11001 * $content: $( '<p>Panel One</p>' ),
11005 * new OO.ui.PanelLayout( {
11006 * $content: $( '<p>Panel Two</p>' ),
11013 * $( 'body' ).append( myStack.$element );
11016 * @extends OO.ui.PanelLayout
11017 * @mixins OO.ui.mixin.GroupElement
11020 * @param {Object} [config] Configuration options
11021 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
11022 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
11024 OO
.ui
.StackLayout
= function OoUiStackLayout( config
) {
11025 // Configuration initialization
11026 config
= $.extend( { scrollable
: true }, config
);
11028 // Parent constructor
11029 OO
.ui
.StackLayout
.parent
.call( this, config
);
11031 // Mixin constructors
11032 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11035 this.currentItem
= null;
11036 this.continuous
= !!config
.continuous
;
11039 this.$element
.addClass( 'oo-ui-stackLayout' );
11040 if ( this.continuous
) {
11041 this.$element
.addClass( 'oo-ui-stackLayout-continuous' );
11042 this.$element
.on( 'scroll', OO
.ui
.debounce( this.onScroll
.bind( this ), 250 ) );
11044 if ( Array
.isArray( config
.items
) ) {
11045 this.addItems( config
.items
);
11051 OO
.inheritClass( OO
.ui
.StackLayout
, OO
.ui
.PanelLayout
);
11052 OO
.mixinClass( OO
.ui
.StackLayout
, OO
.ui
.mixin
.GroupElement
);
11057 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
11058 * {@link #clearItems cleared} or {@link #setItem displayed}.
11061 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
11065 * When used in continuous mode, this event is emitted when the user scrolls down
11066 * far enough such that currentItem is no longer visible.
11068 * @event visibleItemChange
11069 * @param {OO.ui.PanelLayout} panel The next visible item in the layout
11075 * Handle scroll events from the layout element
11077 * @param {jQuery.Event} e
11078 * @fires visibleItemChange
11080 OO
.ui
.StackLayout
.prototype.onScroll = function () {
11082 len
= this.items
.length
,
11083 currentIndex
= this.items
.indexOf( this.currentItem
),
11084 newIndex
= currentIndex
,
11085 containerRect
= this.$element
[ 0 ].getBoundingClientRect();
11087 if ( !containerRect
|| ( !containerRect
.top
&& !containerRect
.bottom
) ) {
11088 // Can't get bounding rect, possibly not attached.
11092 function getRect( item
) {
11093 return item
.$element
[ 0 ].getBoundingClientRect();
11096 function isVisible( item
) {
11097 var rect
= getRect( item
);
11098 return rect
.bottom
> containerRect
.top
&& rect
.top
< containerRect
.bottom
;
11101 currentRect
= getRect( this.currentItem
);
11103 if ( currentRect
.bottom
< containerRect
.top
) {
11104 // Scrolled down past current item
11105 while ( ++newIndex
< len
) {
11106 if ( isVisible( this.items
[ newIndex
] ) ) {
11110 } else if ( currentRect
.top
> containerRect
.bottom
) {
11111 // Scrolled up past current item
11112 while ( --newIndex
>= 0 ) {
11113 if ( isVisible( this.items
[ newIndex
] ) ) {
11119 if ( newIndex
!== currentIndex
) {
11120 this.emit( 'visibleItemChange', this.items
[ newIndex
] );
11125 * Get the current panel.
11127 * @return {OO.ui.Layout|null}
11129 OO
.ui
.StackLayout
.prototype.getCurrentItem = function () {
11130 return this.currentItem
;
11134 * Unset the current item.
11137 * @param {OO.ui.StackLayout} layout
11140 OO
.ui
.StackLayout
.prototype.unsetCurrentItem = function () {
11141 var prevItem
= this.currentItem
;
11142 if ( prevItem
=== null ) {
11146 this.currentItem
= null;
11147 this.emit( 'set', null );
11151 * Add panel layouts to the stack layout.
11153 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
11154 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
11157 * @param {OO.ui.Layout[]} items Panels to add
11158 * @param {number} [index] Index of the insertion point
11161 OO
.ui
.StackLayout
.prototype.addItems = function ( items
, index
) {
11162 // Update the visibility
11163 this.updateHiddenState( items
, this.currentItem
);
11166 OO
.ui
.mixin
.GroupElement
.prototype.addItems
.call( this, items
, index
);
11168 if ( !this.currentItem
&& items
.length
) {
11169 this.setItem( items
[ 0 ] );
11176 * Remove the specified panels from the stack layout.
11178 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
11179 * you may wish to use the #clearItems method instead.
11181 * @param {OO.ui.Layout[]} items Panels to remove
11185 OO
.ui
.StackLayout
.prototype.removeItems = function ( items
) {
11187 OO
.ui
.mixin
.GroupElement
.prototype.removeItems
.call( this, items
);
11189 if ( items
.indexOf( this.currentItem
) !== -1 ) {
11190 if ( this.items
.length
) {
11191 this.setItem( this.items
[ 0 ] );
11193 this.unsetCurrentItem();
11201 * Clear all panels from the stack layout.
11203 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
11204 * a subset of panels, use the #removeItems method.
11209 OO
.ui
.StackLayout
.prototype.clearItems = function () {
11210 this.unsetCurrentItem();
11211 OO
.ui
.mixin
.GroupElement
.prototype.clearItems
.call( this );
11217 * Show the specified panel.
11219 * If another panel is currently displayed, it will be hidden.
11221 * @param {OO.ui.Layout} item Panel to show
11225 OO
.ui
.StackLayout
.prototype.setItem = function ( item
) {
11226 if ( item
!== this.currentItem
) {
11227 this.updateHiddenState( this.items
, item
);
11229 if ( this.items
.indexOf( item
) !== -1 ) {
11230 this.currentItem
= item
;
11231 this.emit( 'set', item
);
11233 this.unsetCurrentItem();
11241 * Update the visibility of all items in case of non-continuous view.
11243 * Ensure all items are hidden except for the selected one.
11244 * This method does nothing when the stack is continuous.
11247 * @param {OO.ui.Layout[]} items Item list iterate over
11248 * @param {OO.ui.Layout} [selectedItem] Selected item to show
11250 OO
.ui
.StackLayout
.prototype.updateHiddenState = function ( items
, selectedItem
) {
11253 if ( !this.continuous
) {
11254 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
11255 if ( !selectedItem
|| selectedItem
!== items
[ i
] ) {
11256 items
[ i
].$element
.addClass( 'oo-ui-element-hidden' );
11259 if ( selectedItem
) {
11260 selectedItem
.$element
.removeClass( 'oo-ui-element-hidden' );
11266 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
11267 * items), with small margins between them. Convenient when you need to put a number of block-level
11268 * widgets on a single line next to each other.
11270 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
11273 * // HorizontalLayout with a text input and a label
11274 * var layout = new OO.ui.HorizontalLayout( {
11276 * new OO.ui.LabelWidget( { label: 'Label' } ),
11277 * new OO.ui.TextInputWidget( { value: 'Text' } )
11280 * $( 'body' ).append( layout.$element );
11283 * @extends OO.ui.Layout
11284 * @mixins OO.ui.mixin.GroupElement
11287 * @param {Object} [config] Configuration options
11288 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
11290 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
11291 // Configuration initialization
11292 config
= config
|| {};
11294 // Parent constructor
11295 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
11297 // Mixin constructors
11298 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11301 this.$element
.addClass( 'oo-ui-horizontalLayout' );
11302 if ( Array
.isArray( config
.items
) ) {
11303 this.addItems( config
.items
);
11309 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
11310 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);
11313 * BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11314 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11315 * and {@link OO.ui.ListToolGroup ListToolGroup}). The {@link OO.ui.Tool tools} in a BarToolGroup are
11316 * displayed by icon in a single row. The title of the tool is displayed when users move the mouse over
11319 * BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar is
11323 * // Example of a BarToolGroup with two tools
11324 * var toolFactory = new OO.ui.ToolFactory();
11325 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11326 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11328 * // We will be placing status text in this element when tools are used
11329 * var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' );
11331 * // Define the tools that we're going to place in our toolbar
11333 * // Create a class inheriting from OO.ui.Tool
11334 * function PictureTool() {
11335 * PictureTool.parent.apply( this, arguments );
11337 * OO.inheritClass( PictureTool, OO.ui.Tool );
11338 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
11339 * // of 'icon' and 'title' (displayed icon and text).
11340 * PictureTool.static.name = 'picture';
11341 * PictureTool.static.icon = 'picture';
11342 * PictureTool.static.title = 'Insert picture';
11343 * // Defines the action that will happen when this tool is selected (clicked).
11344 * PictureTool.prototype.onSelect = function () {
11345 * $area.text( 'Picture tool clicked!' );
11346 * // Never display this tool as "active" (selected).
11347 * this.setActive( false );
11349 * // Make this tool available in our toolFactory and thus our toolbar
11350 * toolFactory.register( PictureTool );
11352 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
11353 * // little popup window (a PopupWidget).
11354 * function HelpTool( toolGroup, config ) {
11355 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11360 * this.popup.$body.append( '<p>I am helpful!</p>' );
11362 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11363 * HelpTool.static.name = 'help';
11364 * HelpTool.static.icon = 'help';
11365 * HelpTool.static.title = 'Help';
11366 * toolFactory.register( HelpTool );
11368 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11369 * // used once (but not all defined tools must be used).
11372 * // 'bar' tool groups display tools by icon only
11374 * include: [ 'picture', 'help' ]
11378 * // Create some UI around the toolbar and place it in the document
11379 * var frame = new OO.ui.PanelLayout( {
11383 * var contentFrame = new OO.ui.PanelLayout( {
11387 * frame.$element.append(
11388 * toolbar.$element,
11389 * contentFrame.$element.append( $area )
11391 * $( 'body' ).append( frame.$element );
11393 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11395 * toolbar.initialize();
11397 * For more information about how to add tools to a bar tool group, please see {@link OO.ui.ToolGroup toolgroup}.
11398 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11400 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11403 * @extends OO.ui.ToolGroup
11406 * @param {OO.ui.Toolbar} toolbar
11407 * @param {Object} [config] Configuration options
11409 OO
.ui
.BarToolGroup
= function OoUiBarToolGroup( toolbar
, config
) {
11410 // Allow passing positional parameters inside the config object
11411 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11413 toolbar
= config
.toolbar
;
11416 // Parent constructor
11417 OO
.ui
.BarToolGroup
.parent
.call( this, toolbar
, config
);
11420 this.$element
.addClass( 'oo-ui-barToolGroup' );
11425 OO
.inheritClass( OO
.ui
.BarToolGroup
, OO
.ui
.ToolGroup
);
11427 /* Static Properties */
11429 OO
.ui
.BarToolGroup
.static.titleTooltips
= true;
11431 OO
.ui
.BarToolGroup
.static.accelTooltips
= true;
11433 OO
.ui
.BarToolGroup
.static.name
= 'bar';
11436 * PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup}
11437 * and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup--an overlaid menu or list of tools with an
11438 * optional icon and label. This class can be used for other base classes that also use this functionality.
11442 * @extends OO.ui.ToolGroup
11443 * @mixins OO.ui.mixin.IconElement
11444 * @mixins OO.ui.mixin.IndicatorElement
11445 * @mixins OO.ui.mixin.LabelElement
11446 * @mixins OO.ui.mixin.TitledElement
11447 * @mixins OO.ui.mixin.ClippableElement
11448 * @mixins OO.ui.mixin.TabIndexedElement
11451 * @param {OO.ui.Toolbar} toolbar
11452 * @param {Object} [config] Configuration options
11453 * @cfg {string} [header] Text to display at the top of the popup
11455 OO
.ui
.PopupToolGroup
= function OoUiPopupToolGroup( toolbar
, config
) {
11456 // Allow passing positional parameters inside the config object
11457 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11459 toolbar
= config
.toolbar
;
11462 // Configuration initialization
11463 config
= config
|| {};
11465 // Parent constructor
11466 OO
.ui
.PopupToolGroup
.parent
.call( this, toolbar
, config
);
11469 this.active
= false;
11470 this.dragging
= false;
11471 this.onBlurHandler
= this.onBlur
.bind( this );
11472 this.$handle
= $( '<span>' );
11474 // Mixin constructors
11475 OO
.ui
.mixin
.IconElement
.call( this, config
);
11476 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
11477 OO
.ui
.mixin
.LabelElement
.call( this, config
);
11478 OO
.ui
.mixin
.TitledElement
.call( this, config
);
11479 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
11480 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
11484 keydown
: this.onHandleMouseKeyDown
.bind( this ),
11485 keyup
: this.onHandleMouseKeyUp
.bind( this ),
11486 mousedown
: this.onHandleMouseKeyDown
.bind( this ),
11487 mouseup
: this.onHandleMouseKeyUp
.bind( this )
11492 .addClass( 'oo-ui-popupToolGroup-handle' )
11493 .append( this.$icon
, this.$label
, this.$indicator
);
11494 // If the pop-up should have a header, add it to the top of the toolGroup.
11495 // Note: If this feature is useful for other widgets, we could abstract it into an
11496 // OO.ui.HeaderedElement mixin constructor.
11497 if ( config
.header
!== undefined ) {
11499 .prepend( $( '<span>' )
11500 .addClass( 'oo-ui-popupToolGroup-header' )
11501 .text( config
.header
)
11505 .addClass( 'oo-ui-popupToolGroup' )
11506 .prepend( this.$handle
);
11511 OO
.inheritClass( OO
.ui
.PopupToolGroup
, OO
.ui
.ToolGroup
);
11512 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.IconElement
);
11513 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.IndicatorElement
);
11514 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.LabelElement
);
11515 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.TitledElement
);
11516 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.ClippableElement
);
11517 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.TabIndexedElement
);
11524 OO
.ui
.PopupToolGroup
.prototype.setDisabled = function () {
11526 OO
.ui
.PopupToolGroup
.parent
.prototype.setDisabled
.apply( this, arguments
);
11528 if ( this.isDisabled() && this.isElementAttached() ) {
11529 this.setActive( false );
11534 * Handle focus being lost.
11536 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
11539 * @param {jQuery.Event} e Mouse up or key up event
11541 OO
.ui
.PopupToolGroup
.prototype.onBlur = function ( e
) {
11542 // Only deactivate when clicking outside the dropdown element
11543 if ( $( e
.target
).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element
[ 0 ] ) {
11544 this.setActive( false );
11551 OO
.ui
.PopupToolGroup
.prototype.onMouseKeyUp = function ( e
) {
11552 // Only close toolgroup when a tool was actually selected
11554 !this.isDisabled() && this.pressed
&& this.pressed
=== this.getTargetTool( e
) &&
11555 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11557 this.setActive( false );
11559 return OO
.ui
.PopupToolGroup
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11563 * Handle mouse up and key up events.
11566 * @param {jQuery.Event} e Mouse up or key up event
11568 OO
.ui
.PopupToolGroup
.prototype.onHandleMouseKeyUp = function ( e
) {
11570 !this.isDisabled() &&
11571 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11578 * Handle mouse down and key down events.
11581 * @param {jQuery.Event} e Mouse down or key down event
11583 OO
.ui
.PopupToolGroup
.prototype.onHandleMouseKeyDown = function ( e
) {
11585 !this.isDisabled() &&
11586 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11588 this.setActive( !this.active
);
11594 * Switch into 'active' mode.
11596 * When active, the popup is visible. A mouseup event anywhere in the document will trigger
11599 OO
.ui
.PopupToolGroup
.prototype.setActive = function ( value
) {
11600 var containerWidth
, containerLeft
;
11602 if ( this.active
!== value
) {
11603 this.active
= value
;
11605 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler
);
11606 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler
);
11608 this.$clippable
.css( 'left', '' );
11609 // Try anchoring the popup to the left first
11610 this.$element
.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
11611 this.toggleClipping( true );
11612 if ( this.isClippedHorizontally() ) {
11613 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
11614 this.toggleClipping( false );
11616 .removeClass( 'oo-ui-popupToolGroup-left' )
11617 .addClass( 'oo-ui-popupToolGroup-right' );
11618 this.toggleClipping( true );
11620 if ( this.isClippedHorizontally() ) {
11621 // Anchoring to the right also caused the popup to clip, so just make it fill the container
11622 containerWidth
= this.$clippableScrollableContainer
.width();
11623 containerLeft
= this.$clippableScrollableContainer
.offset().left
;
11625 this.toggleClipping( false );
11626 this.$element
.removeClass( 'oo-ui-popupToolGroup-right' );
11628 this.$clippable
.css( {
11629 left
: -( this.$element
.offset().left
- containerLeft
),
11630 width
: containerWidth
11634 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler
);
11635 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler
);
11636 this.$element
.removeClass(
11637 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
11639 this.toggleClipping( false );
11645 * ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11646 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11647 * and {@link OO.ui.BarToolGroup BarToolGroup}). The {@link OO.ui.Tool tools} in a ListToolGroup are displayed
11648 * by label in a dropdown menu. The title of the tool is used as the label text. The menu itself can be configured
11649 * with a label, icon, indicator, header, and title.
11651 * ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a ‘More’ option that
11652 * users can select to see the full list of tools. If a collapsed toolgroup is expanded, a ‘Fewer’ option permits
11653 * users to collapse the list again.
11655 * ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the toolbar is set up. The factory
11656 * requires the ListToolGroup's symbolic name, 'list', which is specified along with the other configurations. For more
11657 * information about how to add tools to a ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11660 * // Example of a ListToolGroup
11661 * var toolFactory = new OO.ui.ToolFactory();
11662 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11663 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11665 * // Configure and register two tools
11666 * function SettingsTool() {
11667 * SettingsTool.parent.apply( this, arguments );
11669 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11670 * SettingsTool.static.name = 'settings';
11671 * SettingsTool.static.icon = 'settings';
11672 * SettingsTool.static.title = 'Change settings';
11673 * SettingsTool.prototype.onSelect = function () {
11674 * this.setActive( false );
11676 * toolFactory.register( SettingsTool );
11677 * // Register two more tools, nothing interesting here
11678 * function StuffTool() {
11679 * StuffTool.parent.apply( this, arguments );
11681 * OO.inheritClass( StuffTool, OO.ui.Tool );
11682 * StuffTool.static.name = 'stuff';
11683 * StuffTool.static.icon = 'ellipsis';
11684 * StuffTool.static.title = 'Change the world';
11685 * StuffTool.prototype.onSelect = function () {
11686 * this.setActive( false );
11688 * toolFactory.register( StuffTool );
11691 * // Configurations for list toolgroup.
11693 * label: 'ListToolGroup',
11694 * indicator: 'down',
11696 * title: 'This is the title, displayed when user moves the mouse over the list toolgroup',
11697 * header: 'This is the header',
11698 * include: [ 'settings', 'stuff' ],
11699 * allowCollapse: ['stuff']
11703 * // Create some UI around the toolbar and place it in the document
11704 * var frame = new OO.ui.PanelLayout( {
11708 * frame.$element.append(
11711 * $( 'body' ).append( frame.$element );
11712 * // Build the toolbar. This must be done after the toolbar has been appended to the document.
11713 * toolbar.initialize();
11715 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11717 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11720 * @extends OO.ui.PopupToolGroup
11723 * @param {OO.ui.Toolbar} toolbar
11724 * @param {Object} [config] Configuration options
11725 * @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible tools
11726 * will only be displayed if users click the ‘More’ option displayed at the bottom of the list. If
11727 * the list is expanded, a ‘Fewer’ option permits users to collapse the list again. Any tools that
11728 * are included in the toolgroup, but are not designated as collapsible, will always be displayed.
11729 * To open a collapsible list in its expanded state, set #expanded to 'true'.
11730 * @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as collapsible.
11731 * Unless #expanded is set to true, the collapsible tools will be collapsed when the list is first opened.
11732 * @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools have
11733 * been designated as collapsible. When expanded is set to true, all tools in the group will be displayed
11734 * when the list is first opened. Users can collapse the list with a ‘Fewer’ option at the bottom.
11736 OO
.ui
.ListToolGroup
= function OoUiListToolGroup( toolbar
, config
) {
11737 // Allow passing positional parameters inside the config object
11738 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11740 toolbar
= config
.toolbar
;
11743 // Configuration initialization
11744 config
= config
|| {};
11746 // Properties (must be set before parent constructor, which calls #populate)
11747 this.allowCollapse
= config
.allowCollapse
;
11748 this.forceExpand
= config
.forceExpand
;
11749 this.expanded
= config
.expanded
!== undefined ? config
.expanded
: false;
11750 this.collapsibleTools
= [];
11752 // Parent constructor
11753 OO
.ui
.ListToolGroup
.parent
.call( this, toolbar
, config
);
11756 this.$element
.addClass( 'oo-ui-listToolGroup' );
11761 OO
.inheritClass( OO
.ui
.ListToolGroup
, OO
.ui
.PopupToolGroup
);
11763 /* Static Properties */
11765 OO
.ui
.ListToolGroup
.static.name
= 'list';
11772 OO
.ui
.ListToolGroup
.prototype.populate = function () {
11773 var i
, len
, allowCollapse
= [];
11775 OO
.ui
.ListToolGroup
.parent
.prototype.populate
.call( this );
11777 // Update the list of collapsible tools
11778 if ( this.allowCollapse
!== undefined ) {
11779 allowCollapse
= this.allowCollapse
;
11780 } else if ( this.forceExpand
!== undefined ) {
11781 allowCollapse
= OO
.simpleArrayDifference( Object
.keys( this.tools
), this.forceExpand
);
11784 this.collapsibleTools
= [];
11785 for ( i
= 0, len
= allowCollapse
.length
; i
< len
; i
++ ) {
11786 if ( this.tools
[ allowCollapse
[ i
] ] !== undefined ) {
11787 this.collapsibleTools
.push( this.tools
[ allowCollapse
[ i
] ] );
11791 // Keep at the end, even when tools are added
11792 this.$group
.append( this.getExpandCollapseTool().$element
);
11794 this.getExpandCollapseTool().toggle( this.collapsibleTools
.length
!== 0 );
11795 this.updateCollapsibleState();
11798 OO
.ui
.ListToolGroup
.prototype.getExpandCollapseTool = function () {
11799 var ExpandCollapseTool
;
11800 if ( this.expandCollapseTool
=== undefined ) {
11801 ExpandCollapseTool = function () {
11802 ExpandCollapseTool
.parent
.apply( this, arguments
);
11805 OO
.inheritClass( ExpandCollapseTool
, OO
.ui
.Tool
);
11807 ExpandCollapseTool
.prototype.onSelect = function () {
11808 this.toolGroup
.expanded
= !this.toolGroup
.expanded
;
11809 this.toolGroup
.updateCollapsibleState();
11810 this.setActive( false );
11812 ExpandCollapseTool
.prototype.onUpdateState = function () {
11813 // Do nothing. Tool interface requires an implementation of this function.
11816 ExpandCollapseTool
.static.name
= 'more-fewer';
11818 this.expandCollapseTool
= new ExpandCollapseTool( this );
11820 return this.expandCollapseTool
;
11826 OO
.ui
.ListToolGroup
.prototype.onMouseKeyUp = function ( e
) {
11827 // Do not close the popup when the user wants to show more/fewer tools
11829 $( e
.target
).closest( '.oo-ui-tool-name-more-fewer' ).length
&&
11830 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11832 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
11833 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
11834 return OO
.ui
.ListToolGroup
.parent
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11836 return OO
.ui
.ListToolGroup
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11840 OO
.ui
.ListToolGroup
.prototype.updateCollapsibleState = function () {
11843 this.getExpandCollapseTool()
11844 .setIcon( this.expanded
? 'collapse' : 'expand' )
11845 .setTitle( OO
.ui
.msg( this.expanded
? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
11847 for ( i
= 0, len
= this.collapsibleTools
.length
; i
< len
; i
++ ) {
11848 this.collapsibleTools
[ i
].toggle( this.expanded
);
11853 * MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11854 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.BarToolGroup BarToolGroup}
11855 * and {@link OO.ui.ListToolGroup ListToolGroup}). MenuToolGroups contain selectable {@link OO.ui.Tool tools},
11856 * which are displayed by label in a dropdown menu. The tool's title is used as the label text, and the
11857 * menu label is updated to reflect which tool or tools are currently selected. If no tools are selected,
11858 * the menu label is empty. The menu can be configured with an indicator, icon, title, and/or header.
11860 * MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar
11861 * is set up. Note that all tools must define an {@link OO.ui.Tool#onUpdateState onUpdateState} method if
11862 * a MenuToolGroup is used.
11865 * // Example of a MenuToolGroup
11866 * var toolFactory = new OO.ui.ToolFactory();
11867 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11868 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11870 * // We will be placing status text in this element when tools are used
11871 * var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the dropdown menu.' );
11873 * // Define the tools that we're going to place in our toolbar
11875 * function SettingsTool() {
11876 * SettingsTool.parent.apply( this, arguments );
11877 * this.reallyActive = false;
11879 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11880 * SettingsTool.static.name = 'settings';
11881 * SettingsTool.static.icon = 'settings';
11882 * SettingsTool.static.title = 'Change settings';
11883 * SettingsTool.prototype.onSelect = function () {
11884 * $area.text( 'Settings tool clicked!' );
11885 * // Toggle the active state on each click
11886 * this.reallyActive = !this.reallyActive;
11887 * this.setActive( this.reallyActive );
11888 * // To update the menu label
11889 * this.toolbar.emit( 'updateState' );
11891 * SettingsTool.prototype.onUpdateState = function () {
11893 * toolFactory.register( SettingsTool );
11895 * function StuffTool() {
11896 * StuffTool.parent.apply( this, arguments );
11897 * this.reallyActive = false;
11899 * OO.inheritClass( StuffTool, OO.ui.Tool );
11900 * StuffTool.static.name = 'stuff';
11901 * StuffTool.static.icon = 'ellipsis';
11902 * StuffTool.static.title = 'More stuff';
11903 * StuffTool.prototype.onSelect = function () {
11904 * $area.text( 'More stuff tool clicked!' );
11905 * // Toggle the active state on each click
11906 * this.reallyActive = !this.reallyActive;
11907 * this.setActive( this.reallyActive );
11908 * // To update the menu label
11909 * this.toolbar.emit( 'updateState' );
11911 * StuffTool.prototype.onUpdateState = function () {
11913 * toolFactory.register( StuffTool );
11915 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11916 * // used once (but not all defined tools must be used).
11920 * header: 'This is the (optional) header',
11921 * title: 'This is the (optional) title',
11922 * indicator: 'down',
11923 * include: [ 'settings', 'stuff' ]
11927 * // Create some UI around the toolbar and place it in the document
11928 * var frame = new OO.ui.PanelLayout( {
11932 * var contentFrame = new OO.ui.PanelLayout( {
11936 * frame.$element.append(
11937 * toolbar.$element,
11938 * contentFrame.$element.append( $area )
11940 * $( 'body' ).append( frame.$element );
11942 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11944 * toolbar.initialize();
11945 * toolbar.emit( 'updateState' );
11947 * For more information about how to add tools to a MenuToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11948 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki] [1].
11950 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11953 * @extends OO.ui.PopupToolGroup
11956 * @param {OO.ui.Toolbar} toolbar
11957 * @param {Object} [config] Configuration options
11959 OO
.ui
.MenuToolGroup
= function OoUiMenuToolGroup( toolbar
, config
) {
11960 // Allow passing positional parameters inside the config object
11961 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11963 toolbar
= config
.toolbar
;
11966 // Configuration initialization
11967 config
= config
|| {};
11969 // Parent constructor
11970 OO
.ui
.MenuToolGroup
.parent
.call( this, toolbar
, config
);
11973 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
11976 this.$element
.addClass( 'oo-ui-menuToolGroup' );
11981 OO
.inheritClass( OO
.ui
.MenuToolGroup
, OO
.ui
.PopupToolGroup
);
11983 /* Static Properties */
11985 OO
.ui
.MenuToolGroup
.static.name
= 'menu';
11990 * Handle the toolbar state being updated.
11992 * When the state changes, the title of each active item in the menu will be joined together and
11993 * used as a label for the group. The label will be empty if none of the items are active.
11997 OO
.ui
.MenuToolGroup
.prototype.onUpdateState = function () {
12001 for ( name
in this.tools
) {
12002 if ( this.tools
[ name
].isActive() ) {
12003 labelTexts
.push( this.tools
[ name
].getTitle() );
12007 this.setLabel( labelTexts
.join( ', ' ) || ' ' );
12011 * Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. Each popup tool is configured
12012 * 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
12013 * an #onSelect or #onUpdateState method, as these methods have been implemented already.
12015 * // Example of a popup tool. When selected, a popup tool displays
12016 * // a popup window.
12017 * function HelpTool( toolGroup, config ) {
12018 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
12023 * this.popup.$body.append( '<p>I am helpful!</p>' );
12025 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
12026 * HelpTool.static.name = 'help';
12027 * HelpTool.static.icon = 'help';
12028 * HelpTool.static.title = 'Help';
12029 * toolFactory.register( HelpTool );
12031 * For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. For more information about
12032 * toolbars in genreral, please see the [OOjs UI documentation on MediaWiki][1].
12034 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
12038 * @extends OO.ui.Tool
12039 * @mixins OO.ui.mixin.PopupElement
12042 * @param {OO.ui.ToolGroup} toolGroup
12043 * @param {Object} [config] Configuration options
12045 OO
.ui
.PopupTool
= function OoUiPopupTool( toolGroup
, config
) {
12046 // Allow passing positional parameters inside the config object
12047 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
12048 config
= toolGroup
;
12049 toolGroup
= config
.toolGroup
;
12052 // Parent constructor
12053 OO
.ui
.PopupTool
.parent
.call( this, toolGroup
, config
);
12055 // Mixin constructors
12056 OO
.ui
.mixin
.PopupElement
.call( this, config
);
12060 .addClass( 'oo-ui-popupTool' )
12061 .append( this.popup
.$element
);
12066 OO
.inheritClass( OO
.ui
.PopupTool
, OO
.ui
.Tool
);
12067 OO
.mixinClass( OO
.ui
.PopupTool
, OO
.ui
.mixin
.PopupElement
);
12072 * Handle the tool being selected.
12076 OO
.ui
.PopupTool
.prototype.onSelect = function () {
12077 if ( !this.isDisabled() ) {
12078 this.popup
.toggle();
12080 this.setActive( false );
12085 * Handle the toolbar state being updated.
12089 OO
.ui
.PopupTool
.prototype.onUpdateState = function () {
12090 this.setActive( false );
12094 * A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools}
12095 * and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used
12096 * inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from
12097 * the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list}
12098 * when the ToolGroupTool is selected.
12100 * // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', defined elsewhere.
12102 * function SettingsTool() {
12103 * SettingsTool.parent.apply( this, arguments );
12105 * OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool );
12106 * SettingsTool.static.name = 'settings';
12107 * SettingsTool.static.title = 'Change settings';
12108 * SettingsTool.static.groupConfig = {
12109 * icon: 'settings',
12110 * label: 'ToolGroupTool',
12111 * include: [ 'setting1', 'setting2' ]
12113 * toolFactory.register( SettingsTool );
12115 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
12117 * Please note that this implementation is subject to change per [T74159] [2].
12119 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars#ToolGroupTool
12120 * [2]: https://phabricator.wikimedia.org/T74159
12124 * @extends OO.ui.Tool
12127 * @param {OO.ui.ToolGroup} toolGroup
12128 * @param {Object} [config] Configuration options
12130 OO
.ui
.ToolGroupTool
= function OoUiToolGroupTool( toolGroup
, config
) {
12131 // Allow passing positional parameters inside the config object
12132 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
12133 config
= toolGroup
;
12134 toolGroup
= config
.toolGroup
;
12137 // Parent constructor
12138 OO
.ui
.ToolGroupTool
.parent
.call( this, toolGroup
, config
);
12141 this.innerToolGroup
= this.createGroup( this.constructor.static.groupConfig
);
12144 this.innerToolGroup
.connect( this, { disable
: 'onToolGroupDisable' } );
12147 this.$link
.remove();
12149 .addClass( 'oo-ui-toolGroupTool' )
12150 .append( this.innerToolGroup
.$element
);
12155 OO
.inheritClass( OO
.ui
.ToolGroupTool
, OO
.ui
.Tool
);
12157 /* Static Properties */
12160 * Toolgroup configuration.
12162 * The toolgroup configuration consists of the tools to include, as well as an icon and label
12163 * to use for the bar item. Tools can be included by symbolic name, group, or with the
12164 * wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information.
12166 * @property {Object.<string,Array>}
12168 OO
.ui
.ToolGroupTool
.static.groupConfig
= {};
12173 * Handle the tool being selected.
12177 OO
.ui
.ToolGroupTool
.prototype.onSelect = function () {
12178 this.innerToolGroup
.setActive( !this.innerToolGroup
.active
);
12183 * Synchronize disabledness state of the tool with the inner toolgroup.
12186 * @param {boolean} disabled Element is disabled
12188 OO
.ui
.ToolGroupTool
.prototype.onToolGroupDisable = function ( disabled
) {
12189 this.setDisabled( disabled
);
12193 * Handle the toolbar state being updated.
12197 OO
.ui
.ToolGroupTool
.prototype.onUpdateState = function () {
12198 this.setActive( false );
12202 * Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration.
12204 * @param {Object.<string,Array>} group Toolgroup configuration. Please see {@link OO.ui.ToolGroup toolgroup} for
12205 * more information.
12206 * @return {OO.ui.ListToolGroup}
12208 OO
.ui
.ToolGroupTool
.prototype.createGroup = function ( group
) {
12209 if ( group
.include
=== '*' ) {
12210 // Apply defaults to catch-all groups
12211 if ( group
.label
=== undefined ) {
12212 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
12216 return this.toolbar
.getToolGroupFactory().create( 'list', this.toolbar
, group
);
12220 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
12222 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
12227 * @extends OO.ui.mixin.GroupElement
12230 * @param {Object} [config] Configuration options
12232 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
12233 // Parent constructor
12234 OO
.ui
.mixin
.GroupWidget
.parent
.call( this, config
);
12239 OO
.inheritClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
12244 * Set the disabled state of the widget.
12246 * This will also update the disabled state of child widgets.
12248 * @param {boolean} disabled Disable widget
12251 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
12255 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
12256 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
12258 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
12259 if ( this.items
) {
12260 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
12261 this.items
[ i
].updateDisabled();
12269 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
12271 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
12272 * allows bidirectional communication.
12274 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
12282 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
12289 * Check if widget is disabled.
12291 * Checks parent if present, making disabled state inheritable.
12293 * @return {boolean} Widget is disabled
12295 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
12296 return this.disabled
||
12297 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
12301 * Set group element is in.
12303 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
12306 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
12308 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
12309 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
12311 // Initialize item disabled states
12312 this.updateDisabled();
12318 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
12319 * Controls include moving items up and down, removing items, and adding different kinds of items.
12321 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
12324 * @extends OO.ui.Widget
12325 * @mixins OO.ui.mixin.GroupElement
12326 * @mixins OO.ui.mixin.IconElement
12329 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
12330 * @param {Object} [config] Configuration options
12331 * @cfg {Object} [abilities] List of abilties
12332 * @cfg {boolean} [abilities.move=true] Allow moving movable items
12333 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
12335 OO
.ui
.OutlineControlsWidget
= function OoUiOutlineControlsWidget( outline
, config
) {
12336 // Allow passing positional parameters inside the config object
12337 if ( OO
.isPlainObject( outline
) && config
=== undefined ) {
12339 outline
= config
.outline
;
12342 // Configuration initialization
12343 config
= $.extend( { icon
: 'add' }, config
);
12345 // Parent constructor
12346 OO
.ui
.OutlineControlsWidget
.parent
.call( this, config
);
12348 // Mixin constructors
12349 OO
.ui
.mixin
.GroupElement
.call( this, config
);
12350 OO
.ui
.mixin
.IconElement
.call( this, config
);
12353 this.outline
= outline
;
12354 this.$movers
= $( '<div>' );
12355 this.upButton
= new OO
.ui
.ButtonWidget( {
12358 title
: OO
.ui
.msg( 'ooui-outline-control-move-up' )
12360 this.downButton
= new OO
.ui
.ButtonWidget( {
12363 title
: OO
.ui
.msg( 'ooui-outline-control-move-down' )
12365 this.removeButton
= new OO
.ui
.ButtonWidget( {
12368 title
: OO
.ui
.msg( 'ooui-outline-control-remove' )
12370 this.abilities
= { move: true, remove
: true };
12373 outline
.connect( this, {
12374 select
: 'onOutlineChange',
12375 add
: 'onOutlineChange',
12376 remove
: 'onOutlineChange'
12378 this.upButton
.connect( this, { click
: [ 'emit', 'move', -1 ] } );
12379 this.downButton
.connect( this, { click
: [ 'emit', 'move', 1 ] } );
12380 this.removeButton
.connect( this, { click
: [ 'emit', 'remove' ] } );
12383 this.$element
.addClass( 'oo-ui-outlineControlsWidget' );
12384 this.$group
.addClass( 'oo-ui-outlineControlsWidget-items' );
12386 .addClass( 'oo-ui-outlineControlsWidget-movers' )
12387 .append( this.removeButton
.$element
, this.upButton
.$element
, this.downButton
.$element
);
12388 this.$element
.append( this.$icon
, this.$group
, this.$movers
);
12389 this.setAbilities( config
.abilities
|| {} );
12394 OO
.inheritClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.Widget
);
12395 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.mixin
.GroupElement
);
12396 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.mixin
.IconElement
);
12402 * @param {number} places Number of places to move
12414 * @param {Object} abilities List of abilties
12415 * @param {boolean} [abilities.move] Allow moving movable items
12416 * @param {boolean} [abilities.remove] Allow removing removable items
12418 OO
.ui
.OutlineControlsWidget
.prototype.setAbilities = function ( abilities
) {
12421 for ( ability
in this.abilities
) {
12422 if ( abilities
[ ability
] !== undefined ) {
12423 this.abilities
[ ability
] = !!abilities
[ ability
];
12427 this.onOutlineChange();
12432 * Handle outline change events.
12434 OO
.ui
.OutlineControlsWidget
.prototype.onOutlineChange = function () {
12435 var i
, len
, firstMovable
, lastMovable
,
12436 items
= this.outline
.getItems(),
12437 selectedItem
= this.outline
.getSelectedItem(),
12438 movable
= this.abilities
.move && selectedItem
&& selectedItem
.isMovable(),
12439 removable
= this.abilities
.remove
&& selectedItem
&& selectedItem
.isRemovable();
12443 len
= items
.length
;
12444 while ( ++i
< len
) {
12445 if ( items
[ i
].isMovable() ) {
12446 firstMovable
= items
[ i
];
12452 if ( items
[ i
].isMovable() ) {
12453 lastMovable
= items
[ i
];
12458 this.upButton
.setDisabled( !movable
|| selectedItem
=== firstMovable
);
12459 this.downButton
.setDisabled( !movable
|| selectedItem
=== lastMovable
);
12460 this.removeButton
.setDisabled( !removable
);
12464 * ToggleWidget implements basic behavior of widgets with an on/off state.
12465 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
12469 * @extends OO.ui.Widget
12472 * @param {Object} [config] Configuration options
12473 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
12474 * By default, the toggle is in the 'off' state.
12476 OO
.ui
.ToggleWidget
= function OoUiToggleWidget( config
) {
12477 // Configuration initialization
12478 config
= config
|| {};
12480 // Parent constructor
12481 OO
.ui
.ToggleWidget
.parent
.call( this, config
);
12487 this.$element
.addClass( 'oo-ui-toggleWidget' );
12488 this.setValue( !!config
.value
);
12493 OO
.inheritClass( OO
.ui
.ToggleWidget
, OO
.ui
.Widget
);
12500 * A change event is emitted when the on/off state of the toggle changes.
12502 * @param {boolean} value Value representing the new state of the toggle
12508 * Get the value representing the toggle’s state.
12510 * @return {boolean} The on/off state of the toggle
12512 OO
.ui
.ToggleWidget
.prototype.getValue = function () {
12517 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
12519 * @param {boolean} value The state of the toggle
12523 OO
.ui
.ToggleWidget
.prototype.setValue = function ( value
) {
12525 if ( this.value
!== value
) {
12526 this.value
= value
;
12527 this.emit( 'change', value
);
12528 this.$element
.toggleClass( 'oo-ui-toggleWidget-on', value
);
12529 this.$element
.toggleClass( 'oo-ui-toggleWidget-off', !value
);
12530 this.$element
.attr( 'aria-checked', value
.toString() );
12536 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
12537 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
12538 * removed, and cleared from the group.
12541 * // Example: A ButtonGroupWidget with two buttons
12542 * var button1 = new OO.ui.PopupButtonWidget( {
12543 * label: 'Select a category',
12546 * $content: $( '<p>List of categories...</p>' ),
12551 * var button2 = new OO.ui.ButtonWidget( {
12552 * label: 'Add item'
12554 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
12555 * items: [button1, button2]
12557 * $( 'body' ).append( buttonGroup.$element );
12560 * @extends OO.ui.Widget
12561 * @mixins OO.ui.mixin.GroupElement
12564 * @param {Object} [config] Configuration options
12565 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
12567 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
12568 // Configuration initialization
12569 config
= config
|| {};
12571 // Parent constructor
12572 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
12574 // Mixin constructors
12575 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
12578 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
12579 if ( Array
.isArray( config
.items
) ) {
12580 this.addItems( config
.items
);
12586 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
12587 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
12590 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
12591 * feels, and functionality can be customized via the class’s configuration options
12592 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12595 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
12598 * // A button widget
12599 * var button = new OO.ui.ButtonWidget( {
12600 * label: 'Button with Icon',
12602 * iconTitle: 'Remove'
12604 * $( 'body' ).append( button.$element );
12606 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
12609 * @extends OO.ui.Widget
12610 * @mixins OO.ui.mixin.ButtonElement
12611 * @mixins OO.ui.mixin.IconElement
12612 * @mixins OO.ui.mixin.IndicatorElement
12613 * @mixins OO.ui.mixin.LabelElement
12614 * @mixins OO.ui.mixin.TitledElement
12615 * @mixins OO.ui.mixin.FlaggedElement
12616 * @mixins OO.ui.mixin.TabIndexedElement
12617 * @mixins OO.ui.mixin.AccessKeyedElement
12620 * @param {Object} [config] Configuration options
12621 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
12622 * @cfg {string} [target] The frame or window in which to open the hyperlink.
12623 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
12625 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
12626 // Configuration initialization
12627 config
= config
|| {};
12629 // Parent constructor
12630 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
12632 // Mixin constructors
12633 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
12634 OO
.ui
.mixin
.IconElement
.call( this, config
);
12635 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
12636 OO
.ui
.mixin
.LabelElement
.call( this, config
);
12637 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
12638 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
12639 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
12640 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$button
} ) );
12644 this.target
= null;
12645 this.noFollow
= false;
12648 this.connect( this, { disable
: 'onDisable' } );
12651 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
12653 .addClass( 'oo-ui-buttonWidget' )
12654 .append( this.$button
);
12655 this.setHref( config
.href
);
12656 this.setTarget( config
.target
);
12657 this.setNoFollow( config
.noFollow
);
12662 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
12663 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
12664 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
12665 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
12666 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
12667 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
12668 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
12669 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
12670 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
12677 OO
.ui
.ButtonWidget
.prototype.onMouseDown = function ( e
) {
12678 if ( !this.isDisabled() ) {
12679 // Remove the tab-index while the button is down to prevent the button from stealing focus
12680 this.$button
.removeAttr( 'tabindex' );
12683 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown
.call( this, e
);
12689 OO
.ui
.ButtonWidget
.prototype.onMouseUp = function ( e
) {
12690 if ( !this.isDisabled() ) {
12691 // Restore the tab-index after the button is up to restore the button's accessibility
12692 this.$button
.attr( 'tabindex', this.tabIndex
);
12695 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp
.call( this, e
);
12699 * Get hyperlink location.
12701 * @return {string} Hyperlink location
12703 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
12708 * Get hyperlink target.
12710 * @return {string} Hyperlink target
12712 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
12713 return this.target
;
12717 * Get search engine traversal hint.
12719 * @return {boolean} Whether search engines should avoid traversing this hyperlink
12721 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
12722 return this.noFollow
;
12726 * Set hyperlink location.
12728 * @param {string|null} href Hyperlink location, null to remove
12730 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
12731 href
= typeof href
=== 'string' ? href
: null;
12732 if ( href
!== null ) {
12733 if ( !OO
.ui
.isSafeUrl( href
) ) {
12734 throw new Error( 'Potentially unsafe href provided: ' + href
);
12739 if ( href
!== this.href
) {
12748 * Update the `href` attribute, in case of changes to href or
12754 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
12755 if ( this.href
!== null && !this.isDisabled() ) {
12756 this.$button
.attr( 'href', this.href
);
12758 this.$button
.removeAttr( 'href' );
12765 * Handle disable events.
12768 * @param {boolean} disabled Element is disabled
12770 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
12775 * Set hyperlink target.
12777 * @param {string|null} target Hyperlink target, null to remove
12779 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
12780 target
= typeof target
=== 'string' ? target
: null;
12782 if ( target
!== this.target
) {
12783 this.target
= target
;
12784 if ( target
!== null ) {
12785 this.$button
.attr( 'target', target
);
12787 this.$button
.removeAttr( 'target' );
12795 * Set search engine traversal hint.
12797 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
12799 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
12800 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
12802 if ( noFollow
!== this.noFollow
) {
12803 this.noFollow
= noFollow
;
12805 this.$button
.attr( 'rel', 'nofollow' );
12807 this.$button
.removeAttr( 'rel' );
12815 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
12816 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
12819 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
12820 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12823 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
12826 * @extends OO.ui.ButtonWidget
12827 * @mixins OO.ui.mixin.PendingElement
12830 * @param {Object} [config] Configuration options
12831 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12832 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
12833 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
12834 * for more information about setting modes.
12835 * @cfg {boolean} [framed=false] Render the action button with a frame
12837 OO
.ui
.ActionWidget
= function OoUiActionWidget( config
) {
12838 // Configuration initialization
12839 config
= $.extend( { framed
: false }, config
);
12841 // Parent constructor
12842 OO
.ui
.ActionWidget
.parent
.call( this, config
);
12844 // Mixin constructors
12845 OO
.ui
.mixin
.PendingElement
.call( this, config
);
12848 this.action
= config
.action
|| '';
12849 this.modes
= config
.modes
|| [];
12854 this.$element
.addClass( 'oo-ui-actionWidget' );
12859 OO
.inheritClass( OO
.ui
.ActionWidget
, OO
.ui
.ButtonWidget
);
12860 OO
.mixinClass( OO
.ui
.ActionWidget
, OO
.ui
.mixin
.PendingElement
);
12865 * A resize event is emitted when the size of the widget changes.
12873 * Check if the action is configured to be available in the specified `mode`.
12875 * @param {string} mode Name of mode
12876 * @return {boolean} The action is configured with the mode
12878 OO
.ui
.ActionWidget
.prototype.hasMode = function ( mode
) {
12879 return this.modes
.indexOf( mode
) !== -1;
12883 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12887 OO
.ui
.ActionWidget
.prototype.getAction = function () {
12888 return this.action
;
12892 * Get the symbolic name of the mode or modes for which the action is configured to be available.
12894 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
12895 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
12898 * @return {string[]}
12900 OO
.ui
.ActionWidget
.prototype.getModes = function () {
12901 return this.modes
.slice();
12905 * Emit a resize event if the size has changed.
12910 OO
.ui
.ActionWidget
.prototype.propagateResize = function () {
12913 if ( this.isElementAttached() ) {
12914 width
= this.$element
.width();
12915 height
= this.$element
.height();
12917 if ( width
!== this.width
|| height
!== this.height
) {
12918 this.width
= width
;
12919 this.height
= height
;
12920 this.emit( 'resize' );
12930 OO
.ui
.ActionWidget
.prototype.setIcon = function () {
12932 OO
.ui
.mixin
.IconElement
.prototype.setIcon
.apply( this, arguments
);
12933 this.propagateResize();
12941 OO
.ui
.ActionWidget
.prototype.setLabel = function () {
12943 OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.apply( this, arguments
);
12944 this.propagateResize();
12952 OO
.ui
.ActionWidget
.prototype.setFlags = function () {
12954 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags
.apply( this, arguments
);
12955 this.propagateResize();
12963 OO
.ui
.ActionWidget
.prototype.clearFlags = function () {
12965 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags
.apply( this, arguments
);
12966 this.propagateResize();
12972 * Toggle the visibility of the action button.
12974 * @param {boolean} [show] Show button, omit to toggle visibility
12977 OO
.ui
.ActionWidget
.prototype.toggle = function () {
12979 OO
.ui
.ActionWidget
.parent
.prototype.toggle
.apply( this, arguments
);
12980 this.propagateResize();
12986 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
12987 * which is used to display additional information or options.
12990 * // Example of a popup button.
12991 * var popupButton = new OO.ui.PopupButtonWidget( {
12992 * label: 'Popup button with options',
12995 * $content: $( '<p>Additional options here.</p>' ),
12997 * align: 'force-left'
13000 * // Append the button to the DOM.
13001 * $( 'body' ).append( popupButton.$element );
13004 * @extends OO.ui.ButtonWidget
13005 * @mixins OO.ui.mixin.PopupElement
13008 * @param {Object} [config] Configuration options
13010 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
13011 // Parent constructor
13012 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
13014 // Mixin constructors
13015 OO
.ui
.mixin
.PopupElement
.call( this, config
);
13018 this.connect( this, { click
: 'onAction' } );
13022 .addClass( 'oo-ui-popupButtonWidget' )
13023 .attr( 'aria-haspopup', 'true' )
13024 .append( this.popup
.$element
);
13029 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
13030 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
13035 * Handle the button action being triggered.
13039 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
13040 this.popup
.toggle();
13044 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
13045 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
13046 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
13047 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
13048 * and {@link OO.ui.mixin.LabelElement labels}. Please see
13049 * the [OOjs UI documentation][1] on MediaWiki for more information.
13052 * // Toggle buttons in the 'off' and 'on' state.
13053 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
13054 * label: 'Toggle Button off'
13056 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
13057 * label: 'Toggle Button on',
13060 * // Append the buttons to the DOM.
13061 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
13063 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
13066 * @extends OO.ui.ToggleWidget
13067 * @mixins OO.ui.mixin.ButtonElement
13068 * @mixins OO.ui.mixin.IconElement
13069 * @mixins OO.ui.mixin.IndicatorElement
13070 * @mixins OO.ui.mixin.LabelElement
13071 * @mixins OO.ui.mixin.TitledElement
13072 * @mixins OO.ui.mixin.FlaggedElement
13073 * @mixins OO.ui.mixin.TabIndexedElement
13076 * @param {Object} [config] Configuration options
13077 * @cfg {boolean} [value=false] The toggle button’s initial on/off
13078 * state. By default, the button is in the 'off' state.
13080 OO
.ui
.ToggleButtonWidget
= function OoUiToggleButtonWidget( config
) {
13081 // Configuration initialization
13082 config
= config
|| {};
13084 // Parent constructor
13085 OO
.ui
.ToggleButtonWidget
.parent
.call( this, config
);
13087 // Mixin constructors
13088 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
13089 OO
.ui
.mixin
.IconElement
.call( this, config
);
13090 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
13091 OO
.ui
.mixin
.LabelElement
.call( this, config
);
13092 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
13093 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
13094 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
13097 this.connect( this, { click
: 'onAction' } );
13100 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
13102 .addClass( 'oo-ui-toggleButtonWidget' )
13103 .append( this.$button
);
13108 OO
.inheritClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.ToggleWidget
);
13109 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
13110 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.IconElement
);
13111 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
13112 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.LabelElement
);
13113 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.TitledElement
);
13114 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
13115 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13120 * Handle the button action being triggered.
13124 OO
.ui
.ToggleButtonWidget
.prototype.onAction = function () {
13125 this.setValue( !this.value
);
13131 OO
.ui
.ToggleButtonWidget
.prototype.setValue = function ( value
) {
13133 if ( value
!== this.value
) {
13134 // Might be called from parent constructor before ButtonElement constructor
13135 if ( this.$button
) {
13136 this.$button
.attr( 'aria-pressed', value
.toString() );
13138 this.setActive( value
);
13142 OO
.ui
.ToggleButtonWidget
.parent
.prototype.setValue
.call( this, value
);
13150 OO
.ui
.ToggleButtonWidget
.prototype.setButtonElement = function ( $button
) {
13151 if ( this.$button
) {
13152 this.$button
.removeAttr( 'aria-pressed' );
13154 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement
.call( this, $button
);
13155 this.$button
.attr( 'aria-pressed', this.value
.toString() );
13159 * CapsuleMultiSelectWidgets are something like a {@link OO.ui.ComboBoxWidget combo box widget}
13160 * that allows for selecting multiple values.
13162 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
13165 * // Example: A CapsuleMultiSelectWidget.
13166 * var capsule = new OO.ui.CapsuleMultiSelectWidget( {
13167 * label: 'CapsuleMultiSelectWidget',
13168 * selected: [ 'Option 1', 'Option 3' ],
13171 * new OO.ui.MenuOptionWidget( {
13172 * data: 'Option 1',
13173 * label: 'Option One'
13175 * new OO.ui.MenuOptionWidget( {
13176 * data: 'Option 2',
13177 * label: 'Option Two'
13179 * new OO.ui.MenuOptionWidget( {
13180 * data: 'Option 3',
13181 * label: 'Option Three'
13183 * new OO.ui.MenuOptionWidget( {
13184 * data: 'Option 4',
13185 * label: 'Option Four'
13187 * new OO.ui.MenuOptionWidget( {
13188 * data: 'Option 5',
13189 * label: 'Option Five'
13194 * $( 'body' ).append( capsule.$element );
13196 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13199 * @extends OO.ui.Widget
13200 * @mixins OO.ui.mixin.TabIndexedElement
13201 * @mixins OO.ui.mixin.GroupElement
13204 * @param {Object} [config] Configuration options
13205 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
13206 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
13207 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
13208 * If specified, this popup will be shown instead of the menu (but the menu
13209 * will still be used for item labels and allowArbitrary=false). The widgets
13210 * in the popup should use this.addItemsFromData() or this.addItems() as necessary.
13211 * @cfg {jQuery} [$overlay] Render the menu or popup into a separate layer.
13212 * This configuration is useful in cases where the expanded menu is larger than
13213 * its containing `<div>`. The specified overlay layer is usually on top of
13214 * the containing `<div>` and has a larger area. By default, the menu uses
13215 * relative positioning.
13217 OO
.ui
.CapsuleMultiSelectWidget
= function OoUiCapsuleMultiSelectWidget( config
) {
13220 // Configuration initialization
13221 config
= config
|| {};
13223 // Parent constructor
13224 OO
.ui
.CapsuleMultiSelectWidget
.parent
.call( this, config
);
13226 // Properties (must be set before mixin constructor calls)
13227 this.$input
= config
.popup
? null : $( '<input>' );
13228 this.$handle
= $( '<div>' );
13230 // Mixin constructors
13231 OO
.ui
.mixin
.GroupElement
.call( this, config
);
13232 if ( config
.popup
) {
13233 config
.popup
= $.extend( {}, config
.popup
, {
13237 OO
.ui
.mixin
.PopupElement
.call( this, config
);
13238 $tabFocus
= $( '<span>' );
13239 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: $tabFocus
} ) );
13243 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
13245 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
13246 OO
.ui
.mixin
.IconElement
.call( this, config
);
13249 this.allowArbitrary
= !!config
.allowArbitrary
;
13250 this.$overlay
= config
.$overlay
|| this.$element
;
13251 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
13254 $input
: this.$input
,
13255 $container
: this.$element
,
13256 filterFromInput
: true,
13257 disabled
: this.isDisabled()
13263 if ( this.popup
) {
13265 focus
: this.onFocusForPopup
.bind( this )
13267 this.popup
.$element
.on( 'focusout', this.onPopupFocusOut
.bind( this ) );
13268 if ( this.popup
.$autoCloseIgnore
) {
13269 this.popup
.$autoCloseIgnore
.on( 'focusout', this.onPopupFocusOut
.bind( this ) );
13271 this.popup
.connect( this, {
13272 toggle: function ( visible
) {
13273 $tabFocus
.toggle( !visible
);
13278 focus
: this.onInputFocus
.bind( this ),
13279 blur
: this.onInputBlur
.bind( this ),
13280 'propertychange change click mouseup keydown keyup input cut paste select': this.onInputChange
.bind( this ),
13281 keydown
: this.onKeyDown
.bind( this ),
13282 keypress
: this.onKeyPress
.bind( this )
13285 this.menu
.connect( this, {
13286 choose
: 'onMenuChoose',
13287 add
: 'onMenuItemsChange',
13288 remove
: 'onMenuItemsChange'
13291 click
: this.onClick
.bind( this )
13295 if ( this.$input
) {
13296 this.$input
.prop( 'disabled', this.isDisabled() );
13297 this.$input
.attr( {
13299 'aria-autocomplete': 'list'
13301 this.$input
.width( '1em' );
13303 if ( config
.data
) {
13304 this.setItemsFromData( config
.data
);
13306 this.$group
.addClass( 'oo-ui-capsuleMultiSelectWidget-group' );
13307 this.$handle
.addClass( 'oo-ui-capsuleMultiSelectWidget-handle' )
13308 .append( this.$indicator
, this.$icon
, this.$group
);
13309 this.$element
.addClass( 'oo-ui-capsuleMultiSelectWidget' )
13310 .append( this.$handle
);
13311 if ( this.popup
) {
13312 this.$handle
.append( $tabFocus
);
13313 this.$overlay
.append( this.popup
.$element
);
13315 this.$handle
.append( this.$input
);
13316 this.$overlay
.append( this.menu
.$element
);
13318 this.onMenuItemsChange();
13323 OO
.inheritClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.Widget
);
13324 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.GroupElement
);
13325 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.PopupElement
);
13326 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13327 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.IndicatorElement
);
13328 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.IconElement
);
13335 * A change event is emitted when the set of selected items changes.
13337 * @param {Mixed[]} datas Data of the now-selected items
13343 * Construct a OO.ui.CapsuleItemWidget (or a subclass thereof) from given label and data.
13346 * @param {Mixed} data Custom data of any type.
13347 * @param {string} label The label text.
13348 * @return {OO.ui.CapsuleItemWidget}
13350 OO
.ui
.CapsuleMultiSelectWidget
.prototype.createItemWidget = function ( data
, label
) {
13351 return new OO
.ui
.CapsuleItemWidget( { data
: data
, label
: label
} );
13355 * Get the data of the items in the capsule
13356 * @return {Mixed[]}
13358 OO
.ui
.CapsuleMultiSelectWidget
.prototype.getItemsData = function () {
13359 return $.map( this.getItems(), function ( e
) { return e
.data
; } );
13363 * Set the items in the capsule by providing data
13365 * @param {Mixed[]} datas
13366 * @return {OO.ui.CapsuleMultiSelectWidget}
13368 OO
.ui
.CapsuleMultiSelectWidget
.prototype.setItemsFromData = function ( datas
) {
13371 items
= this.getItems();
13373 $.each( datas
, function ( i
, data
) {
13375 item
= menu
.getItemFromData( data
);
13378 label
= item
.label
;
13379 } else if ( widget
.allowArbitrary
) {
13380 label
= String( data
);
13386 for ( j
= 0; j
< items
.length
; j
++ ) {
13387 if ( items
[ j
].data
=== data
&& items
[ j
].label
=== label
) {
13389 items
.splice( j
, 1 );
13394 item
= widget
.createItemWidget( data
, label
);
13396 widget
.addItems( [ item
], i
);
13399 if ( items
.length
) {
13400 widget
.removeItems( items
);
13407 * Add items to the capsule by providing their data
13409 * @param {Mixed[]} datas
13410 * @return {OO.ui.CapsuleMultiSelectWidget}
13412 OO
.ui
.CapsuleMultiSelectWidget
.prototype.addItemsFromData = function ( datas
) {
13417 $.each( datas
, function ( i
, data
) {
13420 if ( !widget
.getItemFromData( data
) ) {
13421 item
= menu
.getItemFromData( data
);
13423 items
.push( widget
.createItemWidget( data
, item
.label
) );
13424 } else if ( widget
.allowArbitrary
) {
13425 items
.push( widget
.createItemWidget( data
, String( data
) ) );
13430 if ( items
.length
) {
13431 this.addItems( items
);
13438 * Remove items by data
13440 * @param {Mixed[]} datas
13441 * @return {OO.ui.CapsuleMultiSelectWidget}
13443 OO
.ui
.CapsuleMultiSelectWidget
.prototype.removeItemsFromData = function ( datas
) {
13447 $.each( datas
, function ( i
, data
) {
13448 var item
= widget
.getItemFromData( data
);
13450 items
.push( item
);
13454 if ( items
.length
) {
13455 this.removeItems( items
);
13464 OO
.ui
.CapsuleMultiSelectWidget
.prototype.addItems = function ( items
) {
13466 oldItems
= this.items
.slice();
13468 OO
.ui
.mixin
.GroupElement
.prototype.addItems
.call( this, items
);
13470 if ( this.items
.length
!== oldItems
.length
) {
13474 for ( i
= 0, l
= oldItems
.length
; same
&& i
< l
; i
++ ) {
13475 same
= same
&& this.items
[ i
] === oldItems
[ i
];
13479 this.emit( 'change', this.getItemsData() );
13488 OO
.ui
.CapsuleMultiSelectWidget
.prototype.removeItems = function ( items
) {
13490 oldItems
= this.items
.slice();
13492 OO
.ui
.mixin
.GroupElement
.prototype.removeItems
.call( this, items
);
13494 if ( this.items
.length
!== oldItems
.length
) {
13498 for ( i
= 0, l
= oldItems
.length
; same
&& i
< l
; i
++ ) {
13499 same
= same
&& this.items
[ i
] === oldItems
[ i
];
13503 this.emit( 'change', this.getItemsData() );
13512 OO
.ui
.CapsuleMultiSelectWidget
.prototype.clearItems = function () {
13513 if ( this.items
.length
) {
13514 OO
.ui
.mixin
.GroupElement
.prototype.clearItems
.call( this );
13515 this.emit( 'change', this.getItemsData() );
13521 * Get the capsule widget's menu.
13522 * @return {OO.ui.MenuSelectWidget} Menu widget
13524 OO
.ui
.CapsuleMultiSelectWidget
.prototype.getMenu = function () {
13529 * Handle focus events
13532 * @param {jQuery.Event} event
13534 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onInputFocus = function () {
13535 if ( !this.isDisabled() ) {
13536 this.menu
.toggle( true );
13541 * Handle blur events
13544 * @param {jQuery.Event} event
13546 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onInputBlur = function () {
13547 if ( this.allowArbitrary
&& this.$input
.val().trim() !== '' ) {
13548 this.addItemsFromData( [ this.$input
.val() ] );
13554 * Handle focus events
13557 * @param {jQuery.Event} event
13559 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onFocusForPopup = function () {
13560 if ( !this.isDisabled() ) {
13561 this.popup
.setSize( this.$handle
.width() );
13562 this.popup
.toggle( true );
13563 this.popup
.$element
.find( '*' )
13564 .filter( function () { return OO
.ui
.isFocusableElement( $( this ), true ); } )
13571 * Handles popup focus out events.
13574 * @param {Event} e Focus out event
13576 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onPopupFocusOut = function () {
13577 var widget
= this.popup
;
13579 setTimeout( function () {
13581 widget
.isVisible() &&
13582 !OO
.ui
.contains( widget
.$element
[ 0 ], document
.activeElement
, true ) &&
13583 ( !widget
.$autoCloseIgnore
|| !widget
.$autoCloseIgnore
.has( document
.activeElement
).length
)
13585 widget
.toggle( false );
13591 * Handle mouse click events.
13594 * @param {jQuery.Event} e Mouse click event
13596 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onClick = function ( e
) {
13597 if ( e
.which
=== 1 ) {
13604 * Handle key press events.
13607 * @param {jQuery.Event} e Key press event
13609 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onKeyPress = function ( e
) {
13612 if ( !this.isDisabled() ) {
13613 if ( e
.which
=== OO
.ui
.Keys
.ESCAPE
) {
13618 if ( !this.popup
) {
13619 this.menu
.toggle( true );
13620 if ( e
.which
=== OO
.ui
.Keys
.ENTER
) {
13621 item
= this.menu
.getItemFromLabel( this.$input
.val(), true );
13623 this.addItemsFromData( [ item
.data
] );
13625 } else if ( this.allowArbitrary
&& this.$input
.val().trim() !== '' ) {
13626 this.addItemsFromData( [ this.$input
.val() ] );
13632 // Make sure the input gets resized.
13633 setTimeout( this.onInputChange
.bind( this ), 0 );
13639 * Handle key down events.
13642 * @param {jQuery.Event} e Key down event
13644 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onKeyDown = function ( e
) {
13645 if ( !this.isDisabled() ) {
13646 // 'keypress' event is not triggered for Backspace
13647 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.$input
.val() === '' ) {
13648 if ( this.items
.length
) {
13649 this.removeItems( this.items
.slice( -1 ) );
13657 * Handle input change events.
13660 * @param {jQuery.Event} e Event of some sort
13662 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onInputChange = function () {
13663 if ( !this.isDisabled() ) {
13664 this.$input
.width( this.$input
.val().length
+ 'em' );
13669 * Handle menu choose events.
13672 * @param {OO.ui.OptionWidget} item Chosen item
13674 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onMenuChoose = function ( item
) {
13675 if ( item
&& item
.isVisible() ) {
13676 this.addItemsFromData( [ item
.getData() ] );
13682 * Handle menu item change events.
13686 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onMenuItemsChange = function () {
13687 this.setItemsFromData( this.getItemsData() );
13688 this.$element
.toggleClass( 'oo-ui-capsuleMultiSelectWidget-empty', this.menu
.isEmpty() );
13692 * Clear the input field
13695 OO
.ui
.CapsuleMultiSelectWidget
.prototype.clearInput = function () {
13696 if ( this.$input
) {
13697 this.$input
.val( '' );
13698 this.$input
.width( '1em' );
13700 if ( this.popup
) {
13701 this.popup
.toggle( false );
13703 this.menu
.toggle( false );
13704 this.menu
.selectItem();
13705 this.menu
.highlightItem();
13711 OO
.ui
.CapsuleMultiSelectWidget
.prototype.setDisabled = function ( disabled
) {
13715 OO
.ui
.CapsuleMultiSelectWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
13717 if ( this.$input
) {
13718 this.$input
.prop( 'disabled', this.isDisabled() );
13721 this.menu
.setDisabled( this.isDisabled() );
13723 if ( this.popup
) {
13724 this.popup
.setDisabled( this.isDisabled() );
13727 if ( this.items
) {
13728 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
13729 this.items
[ i
].updateDisabled();
13739 * @return {OO.ui.CapsuleMultiSelectWidget}
13741 OO
.ui
.CapsuleMultiSelectWidget
.prototype.focus = function () {
13742 if ( !this.isDisabled() ) {
13743 if ( this.popup
) {
13744 this.popup
.setSize( this.$handle
.width() );
13745 this.popup
.toggle( true );
13746 this.popup
.$element
.find( '*' )
13747 .filter( function () { return OO
.ui
.isFocusableElement( $( this ), true ); } )
13751 this.menu
.toggle( true );
13752 this.$input
.focus();
13759 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiSelectWidget
13760 * CapsuleMultiSelectWidget} to display the selected items.
13763 * @extends OO.ui.Widget
13764 * @mixins OO.ui.mixin.ItemWidget
13765 * @mixins OO.ui.mixin.IndicatorElement
13766 * @mixins OO.ui.mixin.LabelElement
13767 * @mixins OO.ui.mixin.FlaggedElement
13768 * @mixins OO.ui.mixin.TabIndexedElement
13771 * @param {Object} [config] Configuration options
13773 OO
.ui
.CapsuleItemWidget
= function OoUiCapsuleItemWidget( config
) {
13774 // Configuration initialization
13775 config
= config
|| {};
13777 // Parent constructor
13778 OO
.ui
.CapsuleItemWidget
.parent
.call( this, config
);
13780 // Properties (must be set before mixin constructor calls)
13781 this.$indicator
= $( '<span>' );
13783 // Mixin constructors
13784 OO
.ui
.mixin
.ItemWidget
.call( this );
13785 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$indicator
, indicator
: 'clear' } ) );
13786 OO
.ui
.mixin
.LabelElement
.call( this, config
);
13787 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
13788 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$indicator
} ) );
13791 this.$indicator
.on( {
13792 keydown
: this.onCloseKeyDown
.bind( this ),
13793 click
: this.onCloseClick
.bind( this )
13798 .addClass( 'oo-ui-capsuleItemWidget' )
13799 .append( this.$indicator
, this.$label
);
13804 OO
.inheritClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.Widget
);
13805 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.ItemWidget
);
13806 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.IndicatorElement
);
13807 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.LabelElement
);
13808 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.FlaggedElement
);
13809 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13814 * Handle close icon clicks
13815 * @param {jQuery.Event} event
13817 OO
.ui
.CapsuleItemWidget
.prototype.onCloseClick = function () {
13818 var element
= this.getElementGroup();
13820 if ( !this.isDisabled() && element
&& $.isFunction( element
.removeItems
) ) {
13821 element
.removeItems( [ this ] );
13827 * Handle close keyboard events
13828 * @param {jQuery.Event} event Key down event
13830 OO
.ui
.CapsuleItemWidget
.prototype.onCloseKeyDown = function ( e
) {
13831 if ( !this.isDisabled() && $.isFunction( this.getElementGroup().removeItems
) ) {
13832 switch ( e
.which
) {
13833 case OO
.ui
.Keys
.ENTER
:
13834 case OO
.ui
.Keys
.BACKSPACE
:
13835 case OO
.ui
.Keys
.SPACE
:
13836 this.getElementGroup().removeItems( [ this ] );
13843 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
13844 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
13845 * users can interact with it.
13847 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
13848 * OO.ui.DropdownInputWidget instead.
13851 * // Example: A DropdownWidget with a menu that contains three options
13852 * var dropDown = new OO.ui.DropdownWidget( {
13853 * label: 'Dropdown menu: Select a menu option',
13856 * new OO.ui.MenuOptionWidget( {
13860 * new OO.ui.MenuOptionWidget( {
13864 * new OO.ui.MenuOptionWidget( {
13872 * $( 'body' ).append( dropDown.$element );
13874 * dropDown.getMenu().selectItemByData( 'b' );
13876 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
13878 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
13880 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13883 * @extends OO.ui.Widget
13884 * @mixins OO.ui.mixin.IconElement
13885 * @mixins OO.ui.mixin.IndicatorElement
13886 * @mixins OO.ui.mixin.LabelElement
13887 * @mixins OO.ui.mixin.TitledElement
13888 * @mixins OO.ui.mixin.TabIndexedElement
13891 * @param {Object} [config] Configuration options
13892 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
13893 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
13894 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
13895 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
13897 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
13898 // Configuration initialization
13899 config
= $.extend( { indicator
: 'down' }, config
);
13901 // Parent constructor
13902 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
13904 // Properties (must be set before TabIndexedElement constructor call)
13905 this.$handle
= this.$( '<span>' );
13906 this.$overlay
= config
.$overlay
|| this.$element
;
13908 // Mixin constructors
13909 OO
.ui
.mixin
.IconElement
.call( this, config
);
13910 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
13911 OO
.ui
.mixin
.LabelElement
.call( this, config
);
13912 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
13913 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
13916 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend( {
13918 $container
: this.$element
13919 }, config
.menu
) );
13923 click
: this.onClick
.bind( this ),
13924 keypress
: this.onKeyPress
.bind( this )
13926 this.menu
.connect( this, { select
: 'onMenuSelect' } );
13930 .addClass( 'oo-ui-dropdownWidget-handle' )
13931 .append( this.$icon
, this.$label
, this.$indicator
);
13933 .addClass( 'oo-ui-dropdownWidget' )
13934 .append( this.$handle
);
13935 this.$overlay
.append( this.menu
.$element
);
13940 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
13941 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
13942 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
13943 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
13944 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
13945 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13952 * @return {OO.ui.MenuSelectWidget} Menu of widget
13954 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
13959 * Handles menu select events.
13962 * @param {OO.ui.MenuOptionWidget} item Selected menu item
13964 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
13968 this.setLabel( null );
13972 selectedLabel
= item
.getLabel();
13974 // If the label is a DOM element, clone it, because setLabel will append() it
13975 if ( selectedLabel
instanceof jQuery
) {
13976 selectedLabel
= selectedLabel
.clone();
13979 this.setLabel( selectedLabel
);
13983 * Handle mouse click events.
13986 * @param {jQuery.Event} e Mouse click event
13988 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
13989 if ( !this.isDisabled() && e
.which
=== 1 ) {
13990 this.menu
.toggle();
13996 * Handle key press events.
13999 * @param {jQuery.Event} e Key press event
14001 OO
.ui
.DropdownWidget
.prototype.onKeyPress = function ( e
) {
14002 if ( !this.isDisabled() &&
14003 ( ( e
.which
=== OO
.ui
.Keys
.SPACE
&& !this.menu
.isVisible() ) || e
.which
=== OO
.ui
.Keys
.ENTER
)
14005 this.menu
.toggle();
14011 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
14012 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
14013 * OO.ui.mixin.IndicatorElement indicators}.
14014 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14017 * // Example of a file select widget
14018 * var selectFile = new OO.ui.SelectFileWidget();
14019 * $( 'body' ).append( selectFile.$element );
14021 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
14024 * @extends OO.ui.Widget
14025 * @mixins OO.ui.mixin.IconElement
14026 * @mixins OO.ui.mixin.IndicatorElement
14027 * @mixins OO.ui.mixin.PendingElement
14028 * @mixins OO.ui.mixin.LabelElement
14031 * @param {Object} [config] Configuration options
14032 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
14033 * @cfg {string} [placeholder] Text to display when no file is selected.
14034 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
14035 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
14036 * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
14037 * @cfg {boolean} [dragDropUI=false] Deprecated alias for showDropTarget
14039 OO
.ui
.SelectFileWidget
= function OoUiSelectFileWidget( config
) {
14042 // TODO: Remove in next release
14043 if ( config
&& config
.dragDropUI
) {
14044 config
.showDropTarget
= true;
14047 // Configuration initialization
14048 config
= $.extend( {
14050 placeholder
: OO
.ui
.msg( 'ooui-selectfile-placeholder' ),
14051 notsupported
: OO
.ui
.msg( 'ooui-selectfile-not-supported' ),
14053 showDropTarget
: false
14056 // Parent constructor
14057 OO
.ui
.SelectFileWidget
.parent
.call( this, config
);
14059 // Mixin constructors
14060 OO
.ui
.mixin
.IconElement
.call( this, config
);
14061 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
14062 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$info
} ) );
14063 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { autoFitLabel
: true } ) );
14066 this.$info
= $( '<span>' );
14069 this.showDropTarget
= config
.showDropTarget
;
14070 this.isSupported
= this.constructor.static.isSupported();
14071 this.currentFile
= null;
14072 if ( Array
.isArray( config
.accept
) ) {
14073 this.accept
= config
.accept
;
14075 this.accept
= null;
14077 this.placeholder
= config
.placeholder
;
14078 this.notsupported
= config
.notsupported
;
14079 this.onFileSelectedHandler
= this.onFileSelected
.bind( this );
14081 this.selectButton
= new OO
.ui
.ButtonWidget( {
14082 classes
: [ 'oo-ui-selectFileWidget-selectButton' ],
14083 label
: 'Select a file',
14084 disabled
: this.disabled
|| !this.isSupported
14087 this.clearButton
= new OO
.ui
.ButtonWidget( {
14088 classes
: [ 'oo-ui-selectFileWidget-clearButton' ],
14091 disabled
: this.disabled
14095 this.selectButton
.$button
.on( {
14096 keypress
: this.onKeyPress
.bind( this )
14098 this.clearButton
.connect( this, {
14099 click
: 'onClearClick'
14101 if ( config
.droppable
) {
14102 dragHandler
= this.onDragEnterOrOver
.bind( this );
14103 this.$element
.on( {
14104 dragenter
: dragHandler
,
14105 dragover
: dragHandler
,
14106 dragleave
: this.onDragLeave
.bind( this ),
14107 drop
: this.onDrop
.bind( this )
14114 this.$label
.addClass( 'oo-ui-selectFileWidget-label' );
14116 .addClass( 'oo-ui-selectFileWidget-info' )
14117 .append( this.$icon
, this.$label
, this.clearButton
.$element
, this.$indicator
);
14119 .addClass( 'oo-ui-selectFileWidget' )
14120 .append( this.$info
, this.selectButton
.$element
);
14121 if ( config
.droppable
&& config
.showDropTarget
) {
14122 this.$dropTarget
= $( '<div>' )
14123 .addClass( 'oo-ui-selectFileWidget-dropTarget' )
14124 .text( OO
.ui
.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
14126 click
: this.onDropTargetClick
.bind( this )
14128 this.$element
.prepend( this.$dropTarget
);
14134 OO
.inheritClass( OO
.ui
.SelectFileWidget
, OO
.ui
.Widget
);
14135 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.IconElement
);
14136 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.IndicatorElement
);
14137 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.PendingElement
);
14138 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.LabelElement
);
14140 /* Static Properties */
14143 * Check if this widget is supported
14146 * @return {boolean}
14148 OO
.ui
.SelectFileWidget
.static.isSupported = function () {
14150 if ( OO
.ui
.SelectFileWidget
.static.isSupportedCache
=== null ) {
14151 $input
= $( '<input type="file">' );
14152 OO
.ui
.SelectFileWidget
.static.isSupportedCache
= $input
[ 0 ].files
!== undefined;
14154 return OO
.ui
.SelectFileWidget
.static.isSupportedCache
;
14157 OO
.ui
.SelectFileWidget
.static.isSupportedCache
= null;
14164 * A change event is emitted when the on/off state of the toggle changes.
14166 * @param {File|null} value New value
14172 * Get the current value of the field
14174 * @return {File|null}
14176 OO
.ui
.SelectFileWidget
.prototype.getValue = function () {
14177 return this.currentFile
;
14181 * Set the current value of the field
14183 * @param {File|null} file File to select
14185 OO
.ui
.SelectFileWidget
.prototype.setValue = function ( file
) {
14186 if ( this.currentFile
!== file
) {
14187 this.currentFile
= file
;
14189 this.emit( 'change', this.currentFile
);
14194 * Focus the widget.
14196 * Focusses the select file button.
14200 OO
.ui
.SelectFileWidget
.prototype.focus = function () {
14201 this.selectButton
.$button
[ 0 ].focus();
14206 * Update the user interface when a file is selected or unselected
14210 OO
.ui
.SelectFileWidget
.prototype.updateUI = function () {
14212 if ( !this.isSupported
) {
14213 this.$element
.addClass( 'oo-ui-selectFileWidget-notsupported' );
14214 this.$element
.removeClass( 'oo-ui-selectFileWidget-empty' );
14215 this.setLabel( this.notsupported
);
14217 this.$element
.addClass( 'oo-ui-selectFileWidget-supported' );
14218 if ( this.currentFile
) {
14219 this.$element
.removeClass( 'oo-ui-selectFileWidget-empty' );
14221 if ( this.currentFile
.type
!== '' ) {
14222 $label
= $label
.add( $( '<span>' ).addClass( 'oo-ui-selectFileWidget-fileType' ).text( this.currentFile
.type
) );
14224 $label
= $label
.add( $( '<span>' ).text( this.currentFile
.name
) );
14225 this.setLabel( $label
);
14227 this.$element
.addClass( 'oo-ui-selectFileWidget-empty' );
14228 this.setLabel( this.placeholder
);
14232 if ( this.$input
) {
14233 this.$input
.attr( 'title', this.getLabel() );
14238 * Add the input to the widget
14242 OO
.ui
.SelectFileWidget
.prototype.addInput = function () {
14243 if ( this.$input
) {
14244 this.$input
.remove();
14247 if ( !this.isSupported
) {
14248 this.$input
= null;
14252 this.$input
= $( '<input type="file">' );
14253 this.$input
.on( 'change', this.onFileSelectedHandler
);
14254 this.$input
.attr( {
14256 title
: this.getLabel()
14258 if ( this.accept
) {
14259 this.$input
.attr( 'accept', this.accept
.join( ', ' ) );
14261 this.selectButton
.$button
.append( this.$input
);
14265 * Determine if we should accept this file
14268 * @param {string} File MIME type
14269 * @return {boolean}
14271 OO
.ui
.SelectFileWidget
.prototype.isAllowedType = function ( mimeType
) {
14274 if ( !this.accept
|| !mimeType
) {
14278 for ( i
= 0; i
< this.accept
.length
; i
++ ) {
14279 mimeTest
= this.accept
[ i
];
14280 if ( mimeTest
=== mimeType
) {
14282 } else if ( mimeTest
.substr( -2 ) === '/*' ) {
14283 mimeTest
= mimeTest
.substr( 0, mimeTest
.length
- 1 );
14284 if ( mimeType
.substr( 0, mimeTest
.length
) === mimeTest
) {
14294 * Handle file selection from the input
14297 * @param {jQuery.Event} e
14299 OO
.ui
.SelectFileWidget
.prototype.onFileSelected = function ( e
) {
14300 var file
= OO
.getProp( e
.target
, 'files', 0 ) || null;
14302 if ( file
&& !this.isAllowedType( file
.type
) ) {
14306 this.setValue( file
);
14311 * Handle clear button click events.
14315 OO
.ui
.SelectFileWidget
.prototype.onClearClick = function () {
14316 this.setValue( null );
14321 * Handle key press events.
14324 * @param {jQuery.Event} e Key press event
14326 OO
.ui
.SelectFileWidget
.prototype.onKeyPress = function ( e
) {
14327 if ( this.isSupported
&& !this.isDisabled() && this.$input
&&
14328 ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
14330 this.$input
.click();
14336 * Handle drop target click events.
14339 * @param {jQuery.Event} e Key press event
14341 OO
.ui
.SelectFileWidget
.prototype.onDropTargetClick = function () {
14342 if ( this.isSupported
&& !this.isDisabled() && this.$input
) {
14343 this.$input
.click();
14349 * Handle drag enter and over events
14352 * @param {jQuery.Event} e Drag event
14354 OO
.ui
.SelectFileWidget
.prototype.onDragEnterOrOver = function ( e
) {
14356 droppableFile
= false,
14357 dt
= e
.originalEvent
.dataTransfer
;
14359 e
.preventDefault();
14360 e
.stopPropagation();
14362 if ( this.isDisabled() || !this.isSupported
) {
14363 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14364 dt
.dropEffect
= 'none';
14368 // DataTransferItem and File both have a type property, but in Chrome files
14369 // have no information at this point.
14370 itemOrFile
= OO
.getProp( dt
, 'items', 0 ) || OO
.getProp( dt
, 'files', 0 );
14371 if ( itemOrFile
) {
14372 if ( this.isAllowedType( itemOrFile
.type
) ) {
14373 droppableFile
= true;
14375 // dt.types is Array-like, but not an Array
14376 } else if ( Array
.prototype.indexOf
.call( OO
.getProp( dt
, 'types' ) || [], 'Files' ) !== -1 ) {
14377 // File information is not available at this point for security so just assume
14378 // it is acceptable for now.
14379 // https://bugzilla.mozilla.org/show_bug.cgi?id=640534
14380 droppableFile
= true;
14383 this.$element
.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile
);
14384 if ( !droppableFile
) {
14385 dt
.dropEffect
= 'none';
14392 * Handle drag leave events
14395 * @param {jQuery.Event} e Drag event
14397 OO
.ui
.SelectFileWidget
.prototype.onDragLeave = function () {
14398 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14402 * Handle drop events
14405 * @param {jQuery.Event} e Drop event
14407 OO
.ui
.SelectFileWidget
.prototype.onDrop = function ( e
) {
14409 dt
= e
.originalEvent
.dataTransfer
;
14411 e
.preventDefault();
14412 e
.stopPropagation();
14413 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14415 if ( this.isDisabled() || !this.isSupported
) {
14419 file
= OO
.getProp( dt
, 'files', 0 );
14420 if ( file
&& !this.isAllowedType( file
.type
) ) {
14424 this.setValue( file
);
14433 OO
.ui
.SelectFileWidget
.prototype.setDisabled = function ( disabled
) {
14434 OO
.ui
.SelectFileWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
14435 if ( this.selectButton
) {
14436 this.selectButton
.setDisabled( disabled
);
14438 if ( this.clearButton
) {
14439 this.clearButton
.setDisabled( disabled
);
14445 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
14446 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
14447 * for a list of icons included in the library.
14450 * // An icon widget with a label
14451 * var myIcon = new OO.ui.IconWidget( {
14453 * iconTitle: 'Help'
14455 * // Create a label.
14456 * var iconLabel = new OO.ui.LabelWidget( {
14459 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
14461 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
14464 * @extends OO.ui.Widget
14465 * @mixins OO.ui.mixin.IconElement
14466 * @mixins OO.ui.mixin.TitledElement
14467 * @mixins OO.ui.mixin.FlaggedElement
14470 * @param {Object} [config] Configuration options
14472 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
14473 // Configuration initialization
14474 config
= config
|| {};
14476 // Parent constructor
14477 OO
.ui
.IconWidget
.parent
.call( this, config
);
14479 // Mixin constructors
14480 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
14481 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
14482 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
14485 this.$element
.addClass( 'oo-ui-iconWidget' );
14490 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
14491 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
14492 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
14493 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
14495 /* Static Properties */
14497 OO
.ui
.IconWidget
.static.tagName
= 'span';
14500 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
14501 * attention to the status of an item or to clarify the function of a control. For a list of
14502 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
14505 * // Example of an indicator widget
14506 * var indicator1 = new OO.ui.IndicatorWidget( {
14507 * indicator: 'alert'
14510 * // Create a fieldset layout to add a label
14511 * var fieldset = new OO.ui.FieldsetLayout();
14512 * fieldset.addItems( [
14513 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
14515 * $( 'body' ).append( fieldset.$element );
14517 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
14520 * @extends OO.ui.Widget
14521 * @mixins OO.ui.mixin.IndicatorElement
14522 * @mixins OO.ui.mixin.TitledElement
14525 * @param {Object} [config] Configuration options
14527 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
14528 // Configuration initialization
14529 config
= config
|| {};
14531 // Parent constructor
14532 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
14534 // Mixin constructors
14535 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
14536 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
14539 this.$element
.addClass( 'oo-ui-indicatorWidget' );
14544 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
14545 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
14546 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
14548 /* Static Properties */
14550 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
14553 * InputWidget is the base class for all input widgets, which
14554 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
14555 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
14556 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14558 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14562 * @extends OO.ui.Widget
14563 * @mixins OO.ui.mixin.FlaggedElement
14564 * @mixins OO.ui.mixin.TabIndexedElement
14565 * @mixins OO.ui.mixin.TitledElement
14566 * @mixins OO.ui.mixin.AccessKeyedElement
14569 * @param {Object} [config] Configuration options
14570 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
14571 * @cfg {string} [value=''] The value of the input.
14572 * @cfg {string} [accessKey=''] The access key of the input.
14573 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
14574 * before it is accepted.
14576 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
14577 // Configuration initialization
14578 config
= config
|| {};
14580 // Parent constructor
14581 OO
.ui
.InputWidget
.parent
.call( this, config
);
14584 this.$input
= this.getInputElement( config
);
14586 this.inputFilter
= config
.inputFilter
;
14588 // Mixin constructors
14589 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
14590 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
14591 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
14592 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$input
} ) );
14595 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
14599 .addClass( 'oo-ui-inputWidget-input' )
14600 .attr( 'name', config
.name
)
14601 .prop( 'disabled', this.isDisabled() );
14603 .addClass( 'oo-ui-inputWidget' )
14604 .append( this.$input
);
14605 this.setValue( config
.value
);
14606 this.setAccessKey( config
.accessKey
);
14611 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
14612 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
14613 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
14614 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
14615 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
14617 /* Static Properties */
14619 OO
.ui
.InputWidget
.static.supportsSimpleLabel
= true;
14621 /* Static Methods */
14626 OO
.ui
.InputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
14628 state
= OO
.ui
.InputWidget
.parent
.static.gatherPreInfuseState( node
, config
),
14629 $input
= state
.$input
|| $( node
).find( '.oo-ui-inputWidget-input' );
14630 state
.value
= $input
.val();
14631 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
14632 state
.focus
= $input
.is( ':focus' );
14641 * A change event is emitted when the value of the input changes.
14643 * @param {string} value
14649 * Get input element.
14651 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
14652 * different circumstances. The element must have a `value` property (like form elements).
14655 * @param {Object} config Configuration options
14656 * @return {jQuery} Input element
14658 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
14659 return $( '<input>' );
14663 * Handle potentially value-changing events.
14666 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
14668 OO
.ui
.InputWidget
.prototype.onEdit = function () {
14670 if ( !this.isDisabled() ) {
14671 // Allow the stack to clear so the value will be updated
14672 setTimeout( function () {
14673 widget
.setValue( widget
.$input
.val() );
14679 * Get the value of the input.
14681 * @return {string} Input value
14683 OO
.ui
.InputWidget
.prototype.getValue = function () {
14684 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14685 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14686 var value
= this.$input
.val();
14687 if ( this.value
!== value
) {
14688 this.setValue( value
);
14694 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
14696 * @param {boolean} isRTL
14697 * Direction is right-to-left
14699 OO
.ui
.InputWidget
.prototype.setRTL = function ( isRTL
) {
14700 this.$input
.prop( 'dir', isRTL
? 'rtl' : 'ltr' );
14704 * Set the value of the input.
14706 * @param {string} value New value
14710 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
14711 value
= this.cleanUpValue( value
);
14712 // Update the DOM if it has changed. Note that with cleanUpValue, it
14713 // is possible for the DOM value to change without this.value changing.
14714 if ( this.$input
.val() !== value
) {
14715 this.$input
.val( value
);
14717 if ( this.value
!== value
) {
14718 this.value
= value
;
14719 this.emit( 'change', this.value
);
14725 * Set the input's access key.
14726 * FIXME: This is the same code as in OO.ui.mixin.ButtonElement, maybe find a better place for it?
14728 * @param {string} accessKey Input's access key, use empty string to remove
14731 OO
.ui
.InputWidget
.prototype.setAccessKey = function ( accessKey
) {
14732 accessKey
= typeof accessKey
=== 'string' && accessKey
.length
? accessKey
: null;
14734 if ( this.accessKey
!== accessKey
) {
14735 if ( this.$input
) {
14736 if ( accessKey
!== null ) {
14737 this.$input
.attr( 'accesskey', accessKey
);
14739 this.$input
.removeAttr( 'accesskey' );
14742 this.accessKey
= accessKey
;
14749 * Clean up incoming value.
14751 * Ensures value is a string, and converts undefined and null to empty string.
14754 * @param {string} value Original value
14755 * @return {string} Cleaned up value
14757 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
14758 if ( value
=== undefined || value
=== null ) {
14760 } else if ( this.inputFilter
) {
14761 return this.inputFilter( String( value
) );
14763 return String( value
);
14768 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
14769 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
14772 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
14773 if ( !this.isDisabled() ) {
14774 if ( this.$input
.is( ':checkbox, :radio' ) ) {
14775 this.$input
.click();
14777 if ( this.$input
.is( ':input' ) ) {
14778 this.$input
[ 0 ].focus();
14786 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
14787 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
14788 if ( this.$input
) {
14789 this.$input
.prop( 'disabled', this.isDisabled() );
14799 OO
.ui
.InputWidget
.prototype.focus = function () {
14800 this.$input
[ 0 ].focus();
14809 OO
.ui
.InputWidget
.prototype.blur = function () {
14810 this.$input
[ 0 ].blur();
14817 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
14818 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
14819 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
14820 this.setValue( state
.value
);
14822 if ( state
.focus
) {
14828 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
14829 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
14830 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
14831 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
14832 * [OOjs UI documentation on MediaWiki] [1] for more information.
14835 * // A ButtonInputWidget rendered as an HTML button, the default.
14836 * var button = new OO.ui.ButtonInputWidget( {
14837 * label: 'Input button',
14841 * $( 'body' ).append( button.$element );
14843 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
14846 * @extends OO.ui.InputWidget
14847 * @mixins OO.ui.mixin.ButtonElement
14848 * @mixins OO.ui.mixin.IconElement
14849 * @mixins OO.ui.mixin.IndicatorElement
14850 * @mixins OO.ui.mixin.LabelElement
14851 * @mixins OO.ui.mixin.TitledElement
14854 * @param {Object} [config] Configuration options
14855 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
14856 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
14857 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
14858 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
14859 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
14861 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
14862 // Configuration initialization
14863 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
14865 // Properties (must be set before parent constructor, which calls #setValue)
14866 this.useInputTag
= config
.useInputTag
;
14868 // Parent constructor
14869 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
14871 // Mixin constructors
14872 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
14873 OO
.ui
.mixin
.IconElement
.call( this, config
);
14874 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
14875 OO
.ui
.mixin
.LabelElement
.call( this, config
);
14876 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
14879 if ( !config
.useInputTag
) {
14880 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
14882 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
14887 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
14888 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
14889 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
14890 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
14891 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
14892 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
14894 /* Static Properties */
14897 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
14898 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
14900 OO
.ui
.ButtonInputWidget
.static.supportsSimpleLabel
= false;
14908 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
14909 var type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ?
14912 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
14918 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
14920 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
14921 * text, or `null` for no label
14924 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
14925 OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
14927 if ( this.useInputTag
) {
14928 if ( typeof label
=== 'function' ) {
14929 label
= OO
.ui
.resolveMsg( label
);
14931 if ( label
instanceof jQuery
) {
14932 label
= label
.text();
14937 this.$input
.val( label
);
14944 * Set the value of the input.
14946 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
14947 * they do not support {@link #value values}.
14949 * @param {string} value New value
14952 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
14953 if ( !this.useInputTag
) {
14954 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
14960 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
14961 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
14962 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
14963 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
14965 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
14968 * // An example of selected, unselected, and disabled checkbox inputs
14969 * var checkbox1=new OO.ui.CheckboxInputWidget( {
14973 * var checkbox2=new OO.ui.CheckboxInputWidget( {
14976 * var checkbox3=new OO.ui.CheckboxInputWidget( {
14980 * // Create a fieldset layout with fields for each checkbox.
14981 * var fieldset = new OO.ui.FieldsetLayout( {
14982 * label: 'Checkboxes'
14984 * fieldset.addItems( [
14985 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
14986 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
14987 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
14989 * $( 'body' ).append( fieldset.$element );
14991 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14994 * @extends OO.ui.InputWidget
14997 * @param {Object} [config] Configuration options
14998 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
15000 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
15001 // Configuration initialization
15002 config
= config
|| {};
15004 // Parent constructor
15005 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
15009 .addClass( 'oo-ui-checkboxInputWidget' )
15010 // Required for pretty styling in MediaWiki theme
15011 .append( $( '<span>' ) );
15012 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
15017 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
15019 /* Static Methods */
15024 OO
.ui
.CheckboxInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
15026 state
= OO
.ui
.CheckboxInputWidget
.parent
.static.gatherPreInfuseState( node
, config
),
15027 $input
= $( node
).find( '.oo-ui-inputWidget-input' );
15028 state
.$input
= $input
; // shortcut for performance, used in InputWidget
15029 state
.checked
= $input
.prop( 'checked' );
15039 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
15040 return $( '<input type="checkbox" />' );
15046 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
15048 if ( !this.isDisabled() ) {
15049 // Allow the stack to clear so the value will be updated
15050 setTimeout( function () {
15051 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
15057 * Set selection state of this checkbox.
15059 * @param {boolean} state `true` for selected
15062 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
15064 if ( this.selected
!== state
) {
15065 this.selected
= state
;
15066 this.$input
.prop( 'checked', this.selected
);
15067 this.emit( 'change', this.selected
);
15073 * Check if this checkbox is selected.
15075 * @return {boolean} Checkbox is selected
15077 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
15078 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
15079 // it, and we won't know unless they're kind enough to trigger a 'change' event.
15080 var selected
= this.$input
.prop( 'checked' );
15081 if ( this.selected
!== selected
) {
15082 this.setSelected( selected
);
15084 return this.selected
;
15090 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
15091 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
15092 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
15093 this.setSelected( state
.checked
);
15098 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
15099 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15100 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15101 * more information about input widgets.
15103 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
15104 * are no options. If no `value` configuration option is provided, the first option is selected.
15105 * If you need a state representing no value (no option being selected), use a DropdownWidget.
15107 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
15110 * // Example: A DropdownInputWidget with three options
15111 * var dropdownInput = new OO.ui.DropdownInputWidget( {
15113 * { data: 'a', label: 'First' },
15114 * { data: 'b', label: 'Second'},
15115 * { data: 'c', label: 'Third' }
15118 * $( 'body' ).append( dropdownInput.$element );
15120 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15123 * @extends OO.ui.InputWidget
15124 * @mixins OO.ui.mixin.TitledElement
15127 * @param {Object} [config] Configuration options
15128 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15129 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
15131 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
15132 // Configuration initialization
15133 config
= config
|| {};
15135 // Properties (must be done before parent constructor which calls #setDisabled)
15136 this.dropdownWidget
= new OO
.ui
.DropdownWidget( config
.dropdown
);
15138 // Parent constructor
15139 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
15141 // Mixin constructors
15142 OO
.ui
.mixin
.TitledElement
.call( this, config
);
15145 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
15148 this.setOptions( config
.options
|| [] );
15150 .addClass( 'oo-ui-dropdownInputWidget' )
15151 .append( this.dropdownWidget
.$element
);
15156 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
15157 OO
.mixinClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.mixin
.TitledElement
);
15165 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
15166 return $( '<input type="hidden">' );
15170 * Handles menu select events.
15173 * @param {OO.ui.MenuOptionWidget} item Selected menu item
15175 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
15176 this.setValue( item
.getData() );
15182 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
15183 value
= this.cleanUpValue( value
);
15184 this.dropdownWidget
.getMenu().selectItemByData( value
);
15185 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
15192 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
15193 this.dropdownWidget
.setDisabled( state
);
15194 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
15199 * Set the options available for this input.
15201 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15204 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
15206 value
= this.getValue(),
15209 // Rebuild the dropdown menu
15210 this.dropdownWidget
.getMenu()
15212 .addItems( options
.map( function ( opt
) {
15213 var optValue
= widget
.cleanUpValue( opt
.data
);
15214 return new OO
.ui
.MenuOptionWidget( {
15216 label
: opt
.label
!== undefined ? opt
.label
: optValue
15220 // Restore the previous value, or reset to something sensible
15221 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
15222 // Previous value is still available, ensure consistency with the dropdown
15223 this.setValue( value
);
15225 // No longer valid, reset
15226 if ( options
.length
) {
15227 this.setValue( options
[ 0 ].data
);
15237 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
15238 this.dropdownWidget
.getMenu().toggle( true );
15245 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
15246 this.dropdownWidget
.getMenu().toggle( false );
15251 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
15252 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
15253 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
15254 * please see the [OOjs UI documentation on MediaWiki][1].
15256 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15259 * // An example of selected, unselected, and disabled radio inputs
15260 * var radio1 = new OO.ui.RadioInputWidget( {
15264 * var radio2 = new OO.ui.RadioInputWidget( {
15267 * var radio3 = new OO.ui.RadioInputWidget( {
15271 * // Create a fieldset layout with fields for each radio button.
15272 * var fieldset = new OO.ui.FieldsetLayout( {
15273 * label: 'Radio inputs'
15275 * fieldset.addItems( [
15276 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
15277 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
15278 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
15280 * $( 'body' ).append( fieldset.$element );
15282 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15285 * @extends OO.ui.InputWidget
15288 * @param {Object} [config] Configuration options
15289 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
15291 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
15292 // Configuration initialization
15293 config
= config
|| {};
15295 // Parent constructor
15296 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
15300 .addClass( 'oo-ui-radioInputWidget' )
15301 // Required for pretty styling in MediaWiki theme
15302 .append( $( '<span>' ) );
15303 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
15308 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
15310 /* Static Methods */
15315 OO
.ui
.RadioInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
15317 state
= OO
.ui
.RadioInputWidget
.parent
.static.gatherPreInfuseState( node
, config
),
15318 $input
= $( node
).find( '.oo-ui-inputWidget-input' );
15319 state
.$input
= $input
; // shortcut for performance, used in InputWidget
15320 state
.checked
= $input
.prop( 'checked' );
15330 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
15331 return $( '<input type="radio" />' );
15337 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
15338 // RadioInputWidget doesn't track its state.
15342 * Set selection state of this radio button.
15344 * @param {boolean} state `true` for selected
15347 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
15348 // RadioInputWidget doesn't track its state.
15349 this.$input
.prop( 'checked', state
);
15354 * Check if this radio button is selected.
15356 * @return {boolean} Radio is selected
15358 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
15359 return this.$input
.prop( 'checked' );
15365 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
15366 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
15367 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
15368 this.setSelected( state
.checked
);
15373 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
15374 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15375 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15376 * more information about input widgets.
15378 * This and OO.ui.DropdownInputWidget support the same configuration options.
15381 * // Example: A RadioSelectInputWidget with three options
15382 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
15384 * { data: 'a', label: 'First' },
15385 * { data: 'b', label: 'Second'},
15386 * { data: 'c', label: 'Third' }
15389 * $( 'body' ).append( radioSelectInput.$element );
15391 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15394 * @extends OO.ui.InputWidget
15397 * @param {Object} [config] Configuration options
15398 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15400 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
15401 // Configuration initialization
15402 config
= config
|| {};
15404 // Properties (must be done before parent constructor which calls #setDisabled)
15405 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
15407 // Parent constructor
15408 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
15411 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
15414 this.setOptions( config
.options
|| [] );
15416 .addClass( 'oo-ui-radioSelectInputWidget' )
15417 .append( this.radioSelectWidget
.$element
);
15422 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
15424 /* Static Properties */
15426 OO
.ui
.RadioSelectInputWidget
.static.supportsSimpleLabel
= false;
15428 /* Static Methods */
15433 OO
.ui
.RadioSelectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
15434 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
15435 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
15445 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
15446 return $( '<input type="hidden">' );
15450 * Handles menu select events.
15453 * @param {OO.ui.RadioOptionWidget} item Selected menu item
15455 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
15456 this.setValue( item
.getData() );
15462 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
15463 value
= this.cleanUpValue( value
);
15464 this.radioSelectWidget
.selectItemByData( value
);
15465 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
15472 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
15473 this.radioSelectWidget
.setDisabled( state
);
15474 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
15479 * Set the options available for this input.
15481 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15484 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
15486 value
= this.getValue(),
15489 // Rebuild the radioSelect menu
15490 this.radioSelectWidget
15492 .addItems( options
.map( function ( opt
) {
15493 var optValue
= widget
.cleanUpValue( opt
.data
);
15494 return new OO
.ui
.RadioOptionWidget( {
15496 label
: opt
.label
!== undefined ? opt
.label
: optValue
15500 // Restore the previous value, or reset to something sensible
15501 if ( this.radioSelectWidget
.getItemFromData( value
) ) {
15502 // Previous value is still available, ensure consistency with the radioSelect
15503 this.setValue( value
);
15505 // No longer valid, reset
15506 if ( options
.length
) {
15507 this.setValue( options
[ 0 ].data
);
15515 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
15516 * size of the field as well as its presentation. In addition, these widgets can be configured
15517 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
15518 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
15519 * which modifies incoming values rather than validating them.
15520 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
15522 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15525 * // Example of a text input widget
15526 * var textInput = new OO.ui.TextInputWidget( {
15527 * value: 'Text input'
15529 * $( 'body' ).append( textInput.$element );
15531 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15534 * @extends OO.ui.InputWidget
15535 * @mixins OO.ui.mixin.IconElement
15536 * @mixins OO.ui.mixin.IndicatorElement
15537 * @mixins OO.ui.mixin.PendingElement
15538 * @mixins OO.ui.mixin.LabelElement
15541 * @param {Object} [config] Configuration options
15542 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
15543 * 'email' or 'url'. Ignored if `multiline` is true.
15545 * Some values of `type` result in additional behaviors:
15547 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
15548 * empties the text field
15549 * @cfg {string} [placeholder] Placeholder text
15550 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
15551 * instruct the browser to focus this widget.
15552 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
15553 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
15554 * @cfg {boolean} [multiline=false] Allow multiple lines of text
15555 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
15556 * specifies minimum number of rows to display.
15557 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
15558 * Use the #maxRows config to specify a maximum number of displayed rows.
15559 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
15560 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
15561 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
15562 * the value or placeholder text: `'before'` or `'after'`
15563 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
15564 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
15565 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
15566 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
15567 * (the value must contain only numbers); when RegExp, a regular expression that must match the
15568 * value for it to be considered valid; when Function, a function receiving the value as parameter
15569 * that must return true, or promise resolving to true, for it to be considered valid.
15571 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
15572 // Configuration initialization
15573 config
= $.extend( {
15575 labelPosition
: 'after'
15577 if ( config
.type
=== 'search' ) {
15578 if ( config
.icon
=== undefined ) {
15579 config
.icon
= 'search';
15581 // indicator: 'clear' is set dynamically later, depending on value
15583 if ( config
.required
) {
15584 if ( config
.indicator
=== undefined ) {
15585 config
.indicator
= 'required';
15589 // Parent constructor
15590 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
15592 // Mixin constructors
15593 OO
.ui
.mixin
.IconElement
.call( this, config
);
15594 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
15595 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
15596 OO
.ui
.mixin
.LabelElement
.call( this, config
);
15599 this.type
= this.getSaneType( config
);
15600 this.readOnly
= false;
15601 this.multiline
= !!config
.multiline
;
15602 this.autosize
= !!config
.autosize
;
15603 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
15604 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
15605 this.validate
= null;
15606 this.styleHeight
= null;
15608 // Clone for resizing
15609 if ( this.autosize
) {
15610 this.$clone
= this.$input
15612 .insertAfter( this.$input
)
15613 .attr( 'aria-hidden', 'true' )
15614 .addClass( 'oo-ui-element-hidden' );
15617 this.setValidation( config
.validate
);
15618 this.setLabelPosition( config
.labelPosition
);
15622 keypress
: this.onKeyPress
.bind( this ),
15623 blur
: this.onBlur
.bind( this )
15626 focus
: this.onElementAttach
.bind( this )
15628 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
15629 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
15630 this.on( 'labelChange', this.updatePosition
.bind( this ) );
15631 this.connect( this, {
15632 change
: 'onChange',
15633 disable
: 'onDisable'
15638 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
15639 .append( this.$icon
, this.$indicator
);
15640 this.setReadOnly( !!config
.readOnly
);
15641 this.updateSearchIndicator();
15642 if ( config
.placeholder
) {
15643 this.$input
.attr( 'placeholder', config
.placeholder
);
15645 if ( config
.maxLength
!== undefined ) {
15646 this.$input
.attr( 'maxlength', config
.maxLength
);
15648 if ( config
.autofocus
) {
15649 this.$input
.attr( 'autofocus', 'autofocus' );
15651 if ( config
.required
) {
15652 this.$input
.attr( 'required', 'required' );
15653 this.$input
.attr( 'aria-required', 'true' );
15655 if ( config
.autocomplete
=== false ) {
15656 this.$input
.attr( 'autocomplete', 'off' );
15657 // Turning off autocompletion also disables "form caching" when the user navigates to a
15658 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
15660 beforeunload: function () {
15661 this.$input
.removeAttr( 'autocomplete' );
15663 pageshow: function () {
15664 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
15665 // whole page... it shouldn't hurt, though.
15666 this.$input
.attr( 'autocomplete', 'off' );
15670 if ( this.multiline
&& config
.rows
) {
15671 this.$input
.attr( 'rows', config
.rows
);
15673 if ( this.label
|| config
.autosize
) {
15674 this.installParentChangeDetector();
15680 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
15681 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
15682 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
15683 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
15684 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
15686 /* Static Properties */
15688 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
15693 /* Static Methods */
15698 OO
.ui
.TextInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
15700 state
= OO
.ui
.TextInputWidget
.parent
.static.gatherPreInfuseState( node
, config
),
15701 $input
= $( node
).find( '.oo-ui-inputWidget-input' );
15702 state
.$input
= $input
; // shortcut for performance, used in InputWidget
15703 if ( config
.multiline
) {
15704 state
.scrollTop
= $input
.scrollTop();
15712 * An `enter` event is emitted when the user presses 'enter' inside the text box.
15714 * Not emitted if the input is multiline.
15720 * A `resize` event is emitted when autosize is set and the widget resizes
15728 * Handle icon mouse down events.
15731 * @param {jQuery.Event} e Mouse down event
15734 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
15735 if ( e
.which
=== 1 ) {
15736 this.$input
[ 0 ].focus();
15742 * Handle indicator mouse down events.
15745 * @param {jQuery.Event} e Mouse down event
15748 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
15749 if ( e
.which
=== 1 ) {
15750 if ( this.type
=== 'search' ) {
15751 // Clear the text field
15752 this.setValue( '' );
15754 this.$input
[ 0 ].focus();
15760 * Handle key press events.
15763 * @param {jQuery.Event} e Key press event
15764 * @fires enter If enter key is pressed and input is not multiline
15766 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
15767 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
15768 this.emit( 'enter', e
);
15773 * Handle blur events.
15776 * @param {jQuery.Event} e Blur event
15778 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
15779 this.setValidityFlag();
15783 * Handle element attach events.
15786 * @param {jQuery.Event} e Element attach event
15788 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
15789 // Any previously calculated size is now probably invalid if we reattached elsewhere
15790 this.valCache
= null;
15792 this.positionLabel();
15796 * Handle change events.
15798 * @param {string} value
15801 OO
.ui
.TextInputWidget
.prototype.onChange = function () {
15802 this.updateSearchIndicator();
15803 this.setValidityFlag();
15808 * Handle disable events.
15810 * @param {boolean} disabled Element is disabled
15813 OO
.ui
.TextInputWidget
.prototype.onDisable = function () {
15814 this.updateSearchIndicator();
15818 * Check if the input is {@link #readOnly read-only}.
15820 * @return {boolean}
15822 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
15823 return this.readOnly
;
15827 * Set the {@link #readOnly read-only} state of the input.
15829 * @param {boolean} state Make input read-only
15832 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
15833 this.readOnly
= !!state
;
15834 this.$input
.prop( 'readOnly', this.readOnly
);
15835 this.updateSearchIndicator();
15840 * Support function for making #onElementAttach work across browsers.
15842 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
15843 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
15845 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
15846 * first time that the element gets attached to the documented.
15848 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
15849 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
15850 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
15853 if ( MutationObserver
) {
15854 // The new way. If only it wasn't so ugly.
15856 if ( this.$element
.closest( 'html' ).length
) {
15857 // Widget is attached already, do nothing. This breaks the functionality of this function when
15858 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
15859 // would require observation of the whole document, which would hurt performance of other,
15860 // more important code.
15864 // Find topmost node in the tree
15865 topmostNode
= this.$element
[ 0 ];
15866 while ( topmostNode
.parentNode
) {
15867 topmostNode
= topmostNode
.parentNode
;
15870 // We have no way to detect the $element being attached somewhere without observing the entire
15871 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
15872 // parent node of $element, and instead detect when $element is removed from it (and thus
15873 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
15874 // doesn't get attached, we end up back here and create the parent.
15876 mutationObserver
= new MutationObserver( function ( mutations
) {
15877 var i
, j
, removedNodes
;
15878 for ( i
= 0; i
< mutations
.length
; i
++ ) {
15879 removedNodes
= mutations
[ i
].removedNodes
;
15880 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
15881 if ( removedNodes
[ j
] === topmostNode
) {
15882 setTimeout( onRemove
, 0 );
15889 onRemove = function () {
15890 // If the node was attached somewhere else, report it
15891 if ( widget
.$element
.closest( 'html' ).length
) {
15892 widget
.onElementAttach();
15894 mutationObserver
.disconnect();
15895 widget
.installParentChangeDetector();
15898 // Create a fake parent and observe it
15899 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
15900 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
15902 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
15903 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
15904 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
15909 * Automatically adjust the size of the text input.
15911 * This only affects #multiline inputs that are {@link #autosize autosized}.
15916 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
15917 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
, idealHeight
, newHeight
;
15919 if ( this.multiline
&& this.autosize
&& this.$input
.val() !== this.valCache
) {
15921 .val( this.$input
.val() )
15922 .attr( 'rows', this.minRows
)
15923 // Set inline height property to 0 to measure scroll height
15924 .css( 'height', 0 );
15926 this.$clone
.removeClass( 'oo-ui-element-hidden' );
15928 this.valCache
= this.$input
.val();
15930 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
15932 // Remove inline height property to measure natural heights
15933 this.$clone
.css( 'height', '' );
15934 innerHeight
= this.$clone
.innerHeight();
15935 outerHeight
= this.$clone
.outerHeight();
15937 // Measure max rows height
15939 .attr( 'rows', this.maxRows
)
15940 .css( 'height', 'auto' )
15942 maxInnerHeight
= this.$clone
.innerHeight();
15944 // Difference between reported innerHeight and scrollHeight with no scrollbars present
15945 // Equals 1 on Blink-based browsers and 0 everywhere else
15946 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
15947 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
15949 this.$clone
.addClass( 'oo-ui-element-hidden' );
15951 // Only apply inline height when expansion beyond natural height is needed
15952 // Use the difference between the inner and outer height as a buffer
15953 newHeight
= idealHeight
> innerHeight
? idealHeight
+ ( outerHeight
- innerHeight
) : '';
15954 if ( newHeight
!== this.styleHeight
) {
15955 this.$input
.css( 'height', newHeight
);
15956 this.styleHeight
= newHeight
;
15957 this.emit( 'resize' );
15967 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
15968 return config
.multiline
?
15969 $( '<textarea>' ) :
15970 $( '<input type="' + this.getSaneType( config
) + '" />' );
15974 * Get sanitized value for 'type' for given config.
15976 * @param {Object} config Configuration options
15977 * @return {string|null}
15980 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
15981 var type
= [ 'text', 'password', 'search', 'email', 'url' ].indexOf( config
.type
) !== -1 ?
15984 return config
.multiline
? 'multiline' : type
;
15988 * Check if the input supports multiple lines.
15990 * @return {boolean}
15992 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
15993 return !!this.multiline
;
15997 * Check if the input automatically adjusts its size.
15999 * @return {boolean}
16001 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
16002 return !!this.autosize
;
16006 * Focus the input and select a specified range within the text.
16008 * @param {number} from Select from offset
16009 * @param {number} [to] Select to offset, defaults to from
16012 OO
.ui
.TextInputWidget
.prototype.selectRange = function ( from, to
) {
16013 var textRange
, isBackwards
, start
, end
,
16014 element
= this.$input
[ 0 ];
16018 isBackwards
= to
< from;
16019 start
= isBackwards
? to
: from;
16020 end
= isBackwards
? from : to
;
16024 if ( element
.setSelectionRange
) {
16025 element
.setSelectionRange( start
, end
, isBackwards
? 'backward' : 'forward' );
16026 } else if ( element
.createTextRange
) {
16028 textRange
= element
.createTextRange();
16029 textRange
.collapse( true );
16030 textRange
.moveStart( 'character', start
);
16031 textRange
.moveEnd( 'character', end
- start
);
16032 textRange
.select();
16038 * Get the length of the text input value.
16040 * This could differ from the length of #getValue if the
16041 * value gets filtered
16043 * @return {number} Input length
16045 OO
.ui
.TextInputWidget
.prototype.getInputLength = function () {
16046 return this.$input
[ 0 ].value
.length
;
16050 * Focus the input and select the entire text.
16054 OO
.ui
.TextInputWidget
.prototype.select = function () {
16055 return this.selectRange( 0, this.getInputLength() );
16059 * Focus the input and move the cursor to the start.
16063 OO
.ui
.TextInputWidget
.prototype.moveCursorToStart = function () {
16064 return this.selectRange( 0 );
16068 * Focus the input and move the cursor to the end.
16072 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
16073 return this.selectRange( this.getInputLength() );
16077 * Set the validation pattern.
16079 * The validation pattern is either a regular expression, a function, or the symbolic name of a
16080 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
16081 * value must contain only numbers).
16083 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
16084 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
16086 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
16087 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
16088 this.validate
= validate
;
16090 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
16095 * Sets the 'invalid' flag appropriately.
16097 * @param {boolean} [isValid] Optionally override validation result
16099 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
16101 setFlag = function ( valid
) {
16103 widget
.$input
.attr( 'aria-invalid', 'true' );
16105 widget
.$input
.removeAttr( 'aria-invalid' );
16107 widget
.setFlags( { invalid
: !valid
} );
16110 if ( isValid
!== undefined ) {
16111 setFlag( isValid
);
16113 this.getValidity().then( function () {
16122 * Check if a value is valid.
16124 * This method returns a promise that resolves with a boolean `true` if the current value is
16125 * considered valid according to the supplied {@link #validate validation pattern}.
16128 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
16130 OO
.ui
.TextInputWidget
.prototype.isValid = function () {
16133 if ( this.validate
instanceof Function
) {
16134 result
= this.validate( this.getValue() );
16135 if ( $.isFunction( result
.promise
) ) {
16136 return result
.promise();
16138 return $.Deferred().resolve( !!result
).promise();
16141 return $.Deferred().resolve( !!this.getValue().match( this.validate
) ).promise();
16146 * Get the validity of current value.
16148 * This method returns a promise that resolves if the value is valid and rejects if
16149 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
16151 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
16153 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
16154 var result
, promise
;
16156 function rejectOrResolve( valid
) {
16158 return $.Deferred().resolve().promise();
16160 return $.Deferred().reject().promise();
16164 if ( this.validate
instanceof Function
) {
16165 result
= this.validate( this.getValue() );
16167 if ( $.isFunction( result
.promise
) ) {
16168 promise
= $.Deferred();
16170 result
.then( function ( valid
) {
16180 return promise
.promise();
16182 return rejectOrResolve( result
);
16185 return rejectOrResolve( this.getValue().match( this.validate
) );
16190 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
16192 * @param {string} labelPosition Label position, 'before' or 'after'
16195 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
16196 this.labelPosition
= labelPosition
;
16197 this.updatePosition();
16202 * Deprecated alias of #setLabelPosition
16204 * @deprecated Use setLabelPosition instead.
16206 OO
.ui
.TextInputWidget
.prototype.setPosition
=
16207 OO
.ui
.TextInputWidget
.prototype.setLabelPosition
;
16210 * Update the position of the inline label.
16212 * This method is called by #setLabelPosition, and can also be called on its own if
16213 * something causes the label to be mispositioned.
16217 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
16218 var after
= this.labelPosition
=== 'after';
16221 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
16222 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
16224 this.positionLabel();
16230 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
16231 * already empty or when it's not editable.
16233 OO
.ui
.TextInputWidget
.prototype.updateSearchIndicator = function () {
16234 if ( this.type
=== 'search' ) {
16235 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
16236 this.setIndicator( null );
16238 this.setIndicator( 'clear' );
16244 * Position the label by setting the correct padding on the input.
16249 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
16250 var after
, rtl
, property
;
16251 // Clear old values
16253 // Clear old values if present
16255 'padding-right': '',
16259 if ( this.label
) {
16260 this.$element
.append( this.$label
);
16262 this.$label
.detach();
16266 after
= this.labelPosition
=== 'after';
16267 rtl
= this.$element
.css( 'direction' ) === 'rtl';
16268 property
= after
=== rtl
? 'padding-left' : 'padding-right';
16270 this.$input
.css( property
, this.$label
.outerWidth( true ) );
16278 OO
.ui
.TextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
16279 OO
.ui
.TextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
16280 if ( state
.scrollTop
!== undefined ) {
16281 this.$input
.scrollTop( state
.scrollTop
);
16286 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
16287 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
16288 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
16290 * - by typing a value in the text input field. If the value exactly matches the value of a menu
16291 * option, that option will appear to be selected.
16292 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
16295 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
16298 * // Example: A ComboBoxWidget.
16299 * var comboBox = new OO.ui.ComboBoxWidget( {
16300 * label: 'ComboBoxWidget',
16301 * input: { value: 'Option One' },
16304 * new OO.ui.MenuOptionWidget( {
16305 * data: 'Option 1',
16306 * label: 'Option One'
16308 * new OO.ui.MenuOptionWidget( {
16309 * data: 'Option 2',
16310 * label: 'Option Two'
16312 * new OO.ui.MenuOptionWidget( {
16313 * data: 'Option 3',
16314 * label: 'Option Three'
16316 * new OO.ui.MenuOptionWidget( {
16317 * data: 'Option 4',
16318 * label: 'Option Four'
16320 * new OO.ui.MenuOptionWidget( {
16321 * data: 'Option 5',
16322 * label: 'Option Five'
16327 * $( 'body' ).append( comboBox.$element );
16329 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16332 * @extends OO.ui.Widget
16333 * @mixins OO.ui.mixin.TabIndexedElement
16336 * @param {Object} [config] Configuration options
16337 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
16338 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
16339 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
16340 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
16341 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
16343 OO
.ui
.ComboBoxWidget
= function OoUiComboBoxWidget( config
) {
16344 // Configuration initialization
16345 config
= config
|| {};
16347 // Parent constructor
16348 OO
.ui
.ComboBoxWidget
.parent
.call( this, config
);
16350 // Properties (must be set before TabIndexedElement constructor call)
16351 this.$indicator
= this.$( '<span>' );
16353 // Mixin constructors
16354 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$indicator
} ) );
16357 this.$overlay
= config
.$overlay
|| this.$element
;
16358 this.input
= new OO
.ui
.TextInputWidget( $.extend(
16361 $indicator
: this.$indicator
,
16362 disabled
: this.isDisabled()
16366 this.input
.$input
.eq( 0 ).attr( {
16368 'aria-autocomplete': 'list'
16370 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
16374 $container
: this.input
.$element
,
16375 disabled
: this.isDisabled()
16381 this.$indicator
.on( {
16382 click
: this.onClick
.bind( this ),
16383 keypress
: this.onKeyPress
.bind( this )
16385 this.input
.connect( this, {
16386 change
: 'onInputChange',
16387 enter
: 'onInputEnter'
16389 this.menu
.connect( this, {
16390 choose
: 'onMenuChoose',
16391 add
: 'onMenuItemsChange',
16392 remove
: 'onMenuItemsChange'
16396 this.$element
.addClass( 'oo-ui-comboBoxWidget' ).append( this.input
.$element
);
16397 this.$overlay
.append( this.menu
.$element
);
16398 this.onMenuItemsChange();
16403 OO
.inheritClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.Widget
);
16404 OO
.mixinClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.mixin
.TabIndexedElement
);
16409 * Get the combobox's menu.
16410 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
16412 OO
.ui
.ComboBoxWidget
.prototype.getMenu = function () {
16417 * Get the combobox's text input widget.
16418 * @return {OO.ui.TextInputWidget} Text input widget
16420 OO
.ui
.ComboBoxWidget
.prototype.getInput = function () {
16425 * Handle input change events.
16428 * @param {string} value New value
16430 OO
.ui
.ComboBoxWidget
.prototype.onInputChange = function ( value
) {
16431 var match
= this.menu
.getItemFromData( value
);
16433 this.menu
.selectItem( match
);
16434 if ( this.menu
.getHighlightedItem() ) {
16435 this.menu
.highlightItem( match
);
16438 if ( !this.isDisabled() ) {
16439 this.menu
.toggle( true );
16444 * Handle mouse click events.
16447 * @param {jQuery.Event} e Mouse click event
16449 OO
.ui
.ComboBoxWidget
.prototype.onClick = function ( e
) {
16450 if ( !this.isDisabled() && e
.which
=== 1 ) {
16451 this.menu
.toggle();
16452 this.input
.$input
[ 0 ].focus();
16458 * Handle key press events.
16461 * @param {jQuery.Event} e Key press event
16463 OO
.ui
.ComboBoxWidget
.prototype.onKeyPress = function ( e
) {
16464 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
16465 this.menu
.toggle();
16466 this.input
.$input
[ 0 ].focus();
16472 * Handle input enter events.
16476 OO
.ui
.ComboBoxWidget
.prototype.onInputEnter = function () {
16477 if ( !this.isDisabled() ) {
16478 this.menu
.toggle( false );
16483 * Handle menu choose events.
16486 * @param {OO.ui.OptionWidget} item Chosen item
16488 OO
.ui
.ComboBoxWidget
.prototype.onMenuChoose = function ( item
) {
16489 this.input
.setValue( item
.getData() );
16493 * Handle menu item change events.
16497 OO
.ui
.ComboBoxWidget
.prototype.onMenuItemsChange = function () {
16498 var match
= this.menu
.getItemFromData( this.input
.getValue() );
16499 this.menu
.selectItem( match
);
16500 if ( this.menu
.getHighlightedItem() ) {
16501 this.menu
.highlightItem( match
);
16503 this.$element
.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu
.isEmpty() );
16509 OO
.ui
.ComboBoxWidget
.prototype.setDisabled = function ( disabled
) {
16511 OO
.ui
.ComboBoxWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
16513 if ( this.input
) {
16514 this.input
.setDisabled( this.isDisabled() );
16517 this.menu
.setDisabled( this.isDisabled() );
16524 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
16525 * be configured with a `label` option that is set to a string, a label node, or a function:
16527 * - String: a plaintext string
16528 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
16529 * label that includes a link or special styling, such as a gray color or additional graphical elements.
16530 * - Function: a function that will produce a string in the future. Functions are used
16531 * in cases where the value of the label is not currently defined.
16533 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
16534 * will come into focus when the label is clicked.
16537 * // Examples of LabelWidgets
16538 * var label1 = new OO.ui.LabelWidget( {
16539 * label: 'plaintext label'
16541 * var label2 = new OO.ui.LabelWidget( {
16542 * label: $( '<a href="default.html">jQuery label</a>' )
16544 * // Create a fieldset layout with fields for each example
16545 * var fieldset = new OO.ui.FieldsetLayout();
16546 * fieldset.addItems( [
16547 * new OO.ui.FieldLayout( label1 ),
16548 * new OO.ui.FieldLayout( label2 )
16550 * $( 'body' ).append( fieldset.$element );
16553 * @extends OO.ui.Widget
16554 * @mixins OO.ui.mixin.LabelElement
16557 * @param {Object} [config] Configuration options
16558 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
16559 * Clicking the label will focus the specified input field.
16561 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
16562 // Configuration initialization
16563 config
= config
|| {};
16565 // Parent constructor
16566 OO
.ui
.LabelWidget
.parent
.call( this, config
);
16568 // Mixin constructors
16569 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
16570 OO
.ui
.mixin
.TitledElement
.call( this, config
);
16573 this.input
= config
.input
;
16576 if ( this.input
instanceof OO
.ui
.InputWidget
) {
16577 this.$element
.on( 'click', this.onClick
.bind( this ) );
16581 this.$element
.addClass( 'oo-ui-labelWidget' );
16586 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
16587 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
16588 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
16590 /* Static Properties */
16592 OO
.ui
.LabelWidget
.static.tagName
= 'span';
16597 * Handles label mouse click events.
16600 * @param {jQuery.Event} e Mouse click event
16602 OO
.ui
.LabelWidget
.prototype.onClick = function () {
16603 this.input
.simulateLabelClick();
16608 * OptionWidgets are special elements that can be selected and configured with data. The
16609 * data is often unique for each option, but it does not have to be. OptionWidgets are used
16610 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
16611 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
16613 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16616 * @extends OO.ui.Widget
16617 * @mixins OO.ui.mixin.LabelElement
16618 * @mixins OO.ui.mixin.FlaggedElement
16621 * @param {Object} [config] Configuration options
16623 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
16624 // Configuration initialization
16625 config
= config
|| {};
16627 // Parent constructor
16628 OO
.ui
.OptionWidget
.parent
.call( this, config
);
16630 // Mixin constructors
16631 OO
.ui
.mixin
.ItemWidget
.call( this );
16632 OO
.ui
.mixin
.LabelElement
.call( this, config
);
16633 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
16636 this.selected
= false;
16637 this.highlighted
= false;
16638 this.pressed
= false;
16642 .data( 'oo-ui-optionWidget', this )
16643 .attr( 'role', 'option' )
16644 .attr( 'aria-selected', 'false' )
16645 .addClass( 'oo-ui-optionWidget' )
16646 .append( this.$label
);
16651 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
16652 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
16653 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
16654 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
16656 /* Static Properties */
16658 OO
.ui
.OptionWidget
.static.selectable
= true;
16660 OO
.ui
.OptionWidget
.static.highlightable
= true;
16662 OO
.ui
.OptionWidget
.static.pressable
= true;
16664 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
16669 * Check if the option can be selected.
16671 * @return {boolean} Item is selectable
16673 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
16674 return this.constructor.static.selectable
&& !this.isDisabled() && this.isVisible();
16678 * Check if the option can be highlighted. A highlight indicates that the option
16679 * may be selected when a user presses enter or clicks. Disabled items cannot
16682 * @return {boolean} Item is highlightable
16684 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
16685 return this.constructor.static.highlightable
&& !this.isDisabled() && this.isVisible();
16689 * Check if the option can be pressed. The pressed state occurs when a user mouses
16690 * down on an item, but has not yet let go of the mouse.
16692 * @return {boolean} Item is pressable
16694 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
16695 return this.constructor.static.pressable
&& !this.isDisabled() && this.isVisible();
16699 * Check if the option is selected.
16701 * @return {boolean} Item is selected
16703 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
16704 return this.selected
;
16708 * Check if the option is highlighted. A highlight indicates that the
16709 * item may be selected when a user presses enter or clicks.
16711 * @return {boolean} Item is highlighted
16713 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
16714 return this.highlighted
;
16718 * Check if the option is pressed. The pressed state occurs when a user mouses
16719 * down on an item, but has not yet let go of the mouse. The item may appear
16720 * selected, but it will not be selected until the user releases the mouse.
16722 * @return {boolean} Item is pressed
16724 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
16725 return this.pressed
;
16729 * Set the option’s selected state. In general, all modifications to the selection
16730 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
16731 * method instead of this method.
16733 * @param {boolean} [state=false] Select option
16736 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
16737 if ( this.constructor.static.selectable
) {
16738 this.selected
= !!state
;
16740 .toggleClass( 'oo-ui-optionWidget-selected', state
)
16741 .attr( 'aria-selected', state
.toString() );
16742 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
16743 this.scrollElementIntoView();
16745 this.updateThemeClasses();
16751 * Set the option’s highlighted state. In general, all programmatic
16752 * modifications to the highlight should be handled by the
16753 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
16754 * method instead of this method.
16756 * @param {boolean} [state=false] Highlight option
16759 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
16760 if ( this.constructor.static.highlightable
) {
16761 this.highlighted
= !!state
;
16762 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
16763 this.updateThemeClasses();
16769 * Set the option’s pressed state. In general, all
16770 * programmatic modifications to the pressed state should be handled by the
16771 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
16772 * method instead of this method.
16774 * @param {boolean} [state=false] Press option
16777 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
16778 if ( this.constructor.static.pressable
) {
16779 this.pressed
= !!state
;
16780 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
16781 this.updateThemeClasses();
16787 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
16788 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
16789 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
16790 * options. For more information about options and selects, please see the
16791 * [OOjs UI documentation on MediaWiki][1].
16794 * // Decorated options in a select widget
16795 * var select = new OO.ui.SelectWidget( {
16797 * new OO.ui.DecoratedOptionWidget( {
16799 * label: 'Option with icon',
16802 * new OO.ui.DecoratedOptionWidget( {
16804 * label: 'Option with indicator',
16805 * indicator: 'next'
16809 * $( 'body' ).append( select.$element );
16811 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16814 * @extends OO.ui.OptionWidget
16815 * @mixins OO.ui.mixin.IconElement
16816 * @mixins OO.ui.mixin.IndicatorElement
16819 * @param {Object} [config] Configuration options
16821 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
16822 // Parent constructor
16823 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
16825 // Mixin constructors
16826 OO
.ui
.mixin
.IconElement
.call( this, config
);
16827 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
16831 .addClass( 'oo-ui-decoratedOptionWidget' )
16832 .prepend( this.$icon
)
16833 .append( this.$indicator
);
16838 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
16839 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
16840 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
16843 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
16844 * can be selected and configured with data. The class is
16845 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
16846 * [OOjs UI documentation on MediaWiki] [1] for more information.
16848 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
16851 * @extends OO.ui.DecoratedOptionWidget
16852 * @mixins OO.ui.mixin.ButtonElement
16853 * @mixins OO.ui.mixin.TabIndexedElement
16854 * @mixins OO.ui.mixin.TitledElement
16857 * @param {Object} [config] Configuration options
16859 OO
.ui
.ButtonOptionWidget
= function OoUiButtonOptionWidget( config
) {
16860 // Configuration initialization
16861 config
= config
|| {};
16863 // Parent constructor
16864 OO
.ui
.ButtonOptionWidget
.parent
.call( this, config
);
16866 // Mixin constructors
16867 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
16868 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
16869 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, {
16870 $tabIndexed
: this.$button
,
16875 this.$element
.addClass( 'oo-ui-buttonOptionWidget' );
16876 this.$button
.append( this.$element
.contents() );
16877 this.$element
.append( this.$button
);
16882 OO
.inheritClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
16883 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.ButtonElement
);
16884 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.TitledElement
);
16885 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.TabIndexedElement
);
16887 /* Static Properties */
16889 // Allow button mouse down events to pass through so they can be handled by the parent select widget
16890 OO
.ui
.ButtonOptionWidget
.static.cancelButtonMouseDownEvents
= false;
16892 OO
.ui
.ButtonOptionWidget
.static.highlightable
= false;
16899 OO
.ui
.ButtonOptionWidget
.prototype.setSelected = function ( state
) {
16900 OO
.ui
.ButtonOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
16902 if ( this.constructor.static.selectable
) {
16903 this.setActive( state
);
16910 * RadioOptionWidget is an option widget that looks like a radio button.
16911 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
16912 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
16914 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
16917 * @extends OO.ui.OptionWidget
16920 * @param {Object} [config] Configuration options
16922 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
16923 // Configuration initialization
16924 config
= config
|| {};
16926 // Properties (must be done before parent constructor which calls #setDisabled)
16927 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
16929 // Parent constructor
16930 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
16933 this.radio
.$input
.on( 'focus', this.onInputFocus
.bind( this ) );
16936 // Remove implicit role, we're handling it ourselves
16937 this.radio
.$input
.attr( 'role', 'presentation' );
16939 .addClass( 'oo-ui-radioOptionWidget' )
16940 .attr( 'role', 'radio' )
16941 .attr( 'aria-checked', 'false' )
16942 .removeAttr( 'aria-selected' )
16943 .prepend( this.radio
.$element
);
16948 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
16950 /* Static Properties */
16952 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
16954 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
16956 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
16958 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
16963 * @param {jQuery.Event} e Focus event
16966 OO
.ui
.RadioOptionWidget
.prototype.onInputFocus = function () {
16967 this.radio
.$input
.blur();
16968 this.$element
.parent().focus();
16974 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
16975 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
16977 this.radio
.setSelected( state
);
16979 .attr( 'aria-checked', state
.toString() )
16980 .removeAttr( 'aria-selected' );
16988 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
16989 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
16991 this.radio
.setDisabled( this.isDisabled() );
16997 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
16998 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
16999 * the [OOjs UI documentation on MediaWiki] [1] for more information.
17001 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
17004 * @extends OO.ui.DecoratedOptionWidget
17007 * @param {Object} [config] Configuration options
17009 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
17010 // Configuration initialization
17011 config
= $.extend( { icon
: 'check' }, config
);
17013 // Parent constructor
17014 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
17018 .attr( 'role', 'menuitem' )
17019 .addClass( 'oo-ui-menuOptionWidget' );
17024 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
17026 /* Static Properties */
17028 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
17031 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
17032 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
17035 * var myDropdown = new OO.ui.DropdownWidget( {
17038 * new OO.ui.MenuSectionOptionWidget( {
17041 * new OO.ui.MenuOptionWidget( {
17043 * label: 'Welsh Corgi'
17045 * new OO.ui.MenuOptionWidget( {
17047 * label: 'Standard Poodle'
17049 * new OO.ui.MenuSectionOptionWidget( {
17052 * new OO.ui.MenuOptionWidget( {
17059 * $( 'body' ).append( myDropdown.$element );
17062 * @extends OO.ui.DecoratedOptionWidget
17065 * @param {Object} [config] Configuration options
17067 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
17068 // Parent constructor
17069 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
17072 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' );
17077 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
17079 /* Static Properties */
17081 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
17083 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
17086 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
17088 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
17089 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
17093 * @extends OO.ui.DecoratedOptionWidget
17096 * @param {Object} [config] Configuration options
17097 * @cfg {number} [level] Indentation level
17098 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
17100 OO
.ui
.OutlineOptionWidget
= function OoUiOutlineOptionWidget( config
) {
17101 // Configuration initialization
17102 config
= config
|| {};
17104 // Parent constructor
17105 OO
.ui
.OutlineOptionWidget
.parent
.call( this, config
);
17109 this.movable
= !!config
.movable
;
17110 this.removable
= !!config
.removable
;
17113 this.$element
.addClass( 'oo-ui-outlineOptionWidget' );
17114 this.setLevel( config
.level
);
17119 OO
.inheritClass( OO
.ui
.OutlineOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
17121 /* Static Properties */
17123 OO
.ui
.OutlineOptionWidget
.static.highlightable
= false;
17125 OO
.ui
.OutlineOptionWidget
.static.scrollIntoViewOnSelect
= true;
17127 OO
.ui
.OutlineOptionWidget
.static.levelClass
= 'oo-ui-outlineOptionWidget-level-';
17129 OO
.ui
.OutlineOptionWidget
.static.levels
= 3;
17134 * Check if item is movable.
17136 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17138 * @return {boolean} Item is movable
17140 OO
.ui
.OutlineOptionWidget
.prototype.isMovable = function () {
17141 return this.movable
;
17145 * Check if item is removable.
17147 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17149 * @return {boolean} Item is removable
17151 OO
.ui
.OutlineOptionWidget
.prototype.isRemovable = function () {
17152 return this.removable
;
17156 * Get indentation level.
17158 * @return {number} Indentation level
17160 OO
.ui
.OutlineOptionWidget
.prototype.getLevel = function () {
17167 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17169 * @param {boolean} movable Item is movable
17172 OO
.ui
.OutlineOptionWidget
.prototype.setMovable = function ( movable
) {
17173 this.movable
= !!movable
;
17174 this.updateThemeClasses();
17179 * Set removability.
17181 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17183 * @param {boolean} movable Item is removable
17186 OO
.ui
.OutlineOptionWidget
.prototype.setRemovable = function ( removable
) {
17187 this.removable
= !!removable
;
17188 this.updateThemeClasses();
17193 * Set indentation level.
17195 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
17198 OO
.ui
.OutlineOptionWidget
.prototype.setLevel = function ( level
) {
17199 var levels
= this.constructor.static.levels
,
17200 levelClass
= this.constructor.static.levelClass
,
17203 this.level
= level
? Math
.max( 0, Math
.min( levels
- 1, level
) ) : 0;
17205 if ( this.level
=== i
) {
17206 this.$element
.addClass( levelClass
+ i
);
17208 this.$element
.removeClass( levelClass
+ i
);
17211 this.updateThemeClasses();
17217 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
17219 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
17220 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
17224 * @extends OO.ui.OptionWidget
17227 * @param {Object} [config] Configuration options
17229 OO
.ui
.TabOptionWidget
= function OoUiTabOptionWidget( config
) {
17230 // Configuration initialization
17231 config
= config
|| {};
17233 // Parent constructor
17234 OO
.ui
.TabOptionWidget
.parent
.call( this, config
);
17237 this.$element
.addClass( 'oo-ui-tabOptionWidget' );
17242 OO
.inheritClass( OO
.ui
.TabOptionWidget
, OO
.ui
.OptionWidget
);
17244 /* Static Properties */
17246 OO
.ui
.TabOptionWidget
.static.highlightable
= false;
17249 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
17250 * By default, each popup has an anchor that points toward its origin.
17251 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
17254 * // A popup widget.
17255 * var popup = new OO.ui.PopupWidget( {
17256 * $content: $( '<p>Hi there!</p>' ),
17261 * $( 'body' ).append( popup.$element );
17262 * // To display the popup, toggle the visibility to 'true'.
17263 * popup.toggle( true );
17265 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
17268 * @extends OO.ui.Widget
17269 * @mixins OO.ui.mixin.LabelElement
17270 * @mixins OO.ui.mixin.ClippableElement
17273 * @param {Object} [config] Configuration options
17274 * @cfg {number} [width=320] Width of popup in pixels
17275 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
17276 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
17277 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
17278 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
17279 * popup is leaning towards the right of the screen.
17280 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
17281 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
17282 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
17283 * sentence in the given language.
17284 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
17285 * See the [OOjs UI docs on MediaWiki][3] for an example.
17286 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
17287 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
17288 * @cfg {jQuery} [$content] Content to append to the popup's body
17289 * @cfg {jQuery} [$footer] Content to append to the popup's footer
17290 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
17291 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
17292 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
17294 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
17295 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
17297 * @cfg {boolean} [padded] Add padding to the popup's body
17299 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
17300 // Configuration initialization
17301 config
= config
|| {};
17303 // Parent constructor
17304 OO
.ui
.PopupWidget
.parent
.call( this, config
);
17306 // Properties (must be set before ClippableElement constructor call)
17307 this.$body
= $( '<div>' );
17308 this.$popup
= $( '<div>' );
17310 // Mixin constructors
17311 OO
.ui
.mixin
.LabelElement
.call( this, config
);
17312 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, {
17313 $clippable
: this.$body
,
17314 $clippableContainer
: this.$popup
17318 this.$head
= $( '<div>' );
17319 this.$footer
= $( '<div>' );
17320 this.$anchor
= $( '<div>' );
17321 // If undefined, will be computed lazily in updateDimensions()
17322 this.$container
= config
.$container
;
17323 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
17324 this.autoClose
= !!config
.autoClose
;
17325 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
17326 this.transitionTimeout
= null;
17327 this.anchor
= null;
17328 this.width
= config
.width
!== undefined ? config
.width
: 320;
17329 this.height
= config
.height
!== undefined ? config
.height
: null;
17330 this.setAlignment( config
.align
);
17331 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
17332 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
17333 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
17336 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
17339 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
17340 this.$body
.addClass( 'oo-ui-popupWidget-body' );
17341 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
17343 .addClass( 'oo-ui-popupWidget-head' )
17344 .append( this.$label
, this.closeButton
.$element
);
17345 this.$footer
.addClass( 'oo-ui-popupWidget-footer' );
17346 if ( !config
.head
) {
17347 this.$head
.addClass( 'oo-ui-element-hidden' );
17349 if ( !config
.$footer
) {
17350 this.$footer
.addClass( 'oo-ui-element-hidden' );
17353 .addClass( 'oo-ui-popupWidget-popup' )
17354 .append( this.$head
, this.$body
, this.$footer
);
17356 .addClass( 'oo-ui-popupWidget' )
17357 .append( this.$popup
, this.$anchor
);
17358 // Move content, which was added to #$element by OO.ui.Widget, to the body
17359 if ( config
.$content
instanceof jQuery
) {
17360 this.$body
.append( config
.$content
);
17362 if ( config
.$footer
instanceof jQuery
) {
17363 this.$footer
.append( config
.$footer
);
17365 if ( config
.padded
) {
17366 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
17369 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
17370 // that reference properties not initialized at that time of parent class construction
17371 // TODO: Find a better way to handle post-constructor setup
17372 this.visible
= false;
17373 this.$element
.addClass( 'oo-ui-element-hidden' );
17378 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
17379 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
17380 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
17385 * Handles mouse down events.
17388 * @param {MouseEvent} e Mouse down event
17390 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
17392 this.isVisible() &&
17393 !$.contains( this.$element
[ 0 ], e
.target
) &&
17394 ( !this.$autoCloseIgnore
|| !this.$autoCloseIgnore
.has( e
.target
).length
)
17396 this.toggle( false );
17401 * Bind mouse down listener.
17405 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
17406 // Capture clicks outside popup
17407 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler
);
17411 * Handles close button click events.
17415 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
17416 if ( this.isVisible() ) {
17417 this.toggle( false );
17422 * Unbind mouse down listener.
17426 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
17427 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler
);
17431 * Handles key down events.
17434 * @param {KeyboardEvent} e Key down event
17436 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
17438 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
17441 this.toggle( false );
17442 e
.preventDefault();
17443 e
.stopPropagation();
17448 * Bind key down listener.
17452 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
17453 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler
);
17457 * Unbind key down listener.
17461 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
17462 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler
);
17466 * Show, hide, or toggle the visibility of the anchor.
17468 * @param {boolean} [show] Show anchor, omit to toggle
17470 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
17471 show
= show
=== undefined ? !this.anchored
: !!show
;
17473 if ( this.anchored
!== show
) {
17475 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
17477 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
17479 this.anchored
= show
;
17484 * Check if the anchor is visible.
17486 * @return {boolean} Anchor is visible
17488 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
17489 return this.anchor
;
17495 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
17497 show
= show
=== undefined ? !this.isVisible() : !!show
;
17499 change
= show
!== this.isVisible();
17502 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
17506 if ( this.autoClose
) {
17507 this.bindMouseDownListener();
17508 this.bindKeyDownListener();
17510 this.updateDimensions();
17511 this.toggleClipping( true );
17513 this.toggleClipping( false );
17514 if ( this.autoClose
) {
17515 this.unbindMouseDownListener();
17516 this.unbindKeyDownListener();
17525 * Set the size of the popup.
17527 * Changing the size may also change the popup's position depending on the alignment.
17529 * @param {number} width Width in pixels
17530 * @param {number} height Height in pixels
17531 * @param {boolean} [transition=false] Use a smooth transition
17534 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
17535 this.width
= width
;
17536 this.height
= height
!== undefined ? height
: null;
17537 if ( this.isVisible() ) {
17538 this.updateDimensions( transition
);
17543 * Update the size and position.
17545 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
17546 * be called automatically.
17548 * @param {boolean} [transition=false] Use a smooth transition
17551 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
17552 var popupOffset
, originOffset
, containerLeft
, containerWidth
, containerRight
,
17553 popupLeft
, popupRight
, overlapLeft
, overlapRight
, anchorWidth
,
17554 align
= this.align
,
17557 if ( !this.$container
) {
17558 // Lazy-initialize $container if not specified in constructor
17559 this.$container
= $( this.getClosestScrollableElementContainer() );
17562 // Set height and width before measuring things, since it might cause our measurements
17563 // to change (e.g. due to scrollbars appearing or disappearing)
17566 height
: this.height
!== null ? this.height
: 'auto'
17569 // If we are in RTL, we need to flip the alignment, unless it is center
17570 if ( align
=== 'forwards' || align
=== 'backwards' ) {
17571 if ( this.$container
.css( 'direction' ) === 'rtl' ) {
17572 align
= ( { forwards
: 'force-left', backwards
: 'force-right' } )[ this.align
];
17574 align
= ( { forwards
: 'force-right', backwards
: 'force-left' } )[ this.align
];
17579 // Compute initial popupOffset based on alignment
17580 popupOffset
= this.width
* ( { 'force-left': -1, center
: -0.5, 'force-right': 0 } )[ align
];
17582 // Figure out if this will cause the popup to go beyond the edge of the container
17583 originOffset
= this.$element
.offset().left
;
17584 containerLeft
= this.$container
.offset().left
;
17585 containerWidth
= this.$container
.innerWidth();
17586 containerRight
= containerLeft
+ containerWidth
;
17587 popupLeft
= popupOffset
- this.containerPadding
;
17588 popupRight
= popupOffset
+ this.containerPadding
+ this.width
+ this.containerPadding
;
17589 overlapLeft
= ( originOffset
+ popupLeft
) - containerLeft
;
17590 overlapRight
= containerRight
- ( originOffset
+ popupRight
);
17592 // Adjust offset to make the popup not go beyond the edge, if needed
17593 if ( overlapRight
< 0 ) {
17594 popupOffset
+= overlapRight
;
17595 } else if ( overlapLeft
< 0 ) {
17596 popupOffset
-= overlapLeft
;
17599 // Adjust offset to avoid anchor being rendered too close to the edge
17600 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
17601 // TODO: Find a measurement that works for CSS anchors and image anchors
17602 anchorWidth
= this.$anchor
[ 0 ].scrollWidth
* 2;
17603 if ( popupOffset
+ this.width
< anchorWidth
) {
17604 popupOffset
= anchorWidth
- this.width
;
17605 } else if ( -popupOffset
< anchorWidth
) {
17606 popupOffset
= -anchorWidth
;
17609 // Prevent transition from being interrupted
17610 clearTimeout( this.transitionTimeout
);
17611 if ( transition
) {
17612 // Enable transition
17613 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
17616 // Position body relative to anchor
17617 this.$popup
.css( 'margin-left', popupOffset
);
17619 if ( transition
) {
17620 // Prevent transitioning after transition is complete
17621 this.transitionTimeout
= setTimeout( function () {
17622 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
17625 // Prevent transitioning immediately
17626 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
17629 // Reevaluate clipping state since we've relocated and resized the popup
17636 * Set popup alignment
17637 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17638 * `backwards` or `forwards`.
17640 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
17641 // Validate alignment and transform deprecated values
17642 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
17643 this.align
= { left
: 'force-right', right
: 'force-left' }[ align
] || align
;
17645 this.align
= 'center';
17650 * Get popup alignment
17651 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17652 * `backwards` or `forwards`.
17654 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
17659 * Progress bars visually display the status of an operation, such as a download,
17660 * and can be either determinate or indeterminate:
17662 * - **determinate** process bars show the percent of an operation that is complete.
17664 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
17665 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
17666 * not use percentages.
17668 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
17671 * // Examples of determinate and indeterminate progress bars.
17672 * var progressBar1 = new OO.ui.ProgressBarWidget( {
17675 * var progressBar2 = new OO.ui.ProgressBarWidget();
17677 * // Create a FieldsetLayout to layout progress bars
17678 * var fieldset = new OO.ui.FieldsetLayout;
17679 * fieldset.addItems( [
17680 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
17681 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
17683 * $( 'body' ).append( fieldset.$element );
17686 * @extends OO.ui.Widget
17689 * @param {Object} [config] Configuration options
17690 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
17691 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
17692 * By default, the progress bar is indeterminate.
17694 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
17695 // Configuration initialization
17696 config
= config
|| {};
17698 // Parent constructor
17699 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
17702 this.$bar
= $( '<div>' );
17703 this.progress
= null;
17706 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
17707 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
17710 role
: 'progressbar',
17711 'aria-valuemin': 0,
17712 'aria-valuemax': 100
17714 .addClass( 'oo-ui-progressBarWidget' )
17715 .append( this.$bar
);
17720 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
17722 /* Static Properties */
17724 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
17729 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
17731 * @return {number|boolean} Progress percent
17733 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
17734 return this.progress
;
17738 * Set the percent of the process completed or `false` for an indeterminate process.
17740 * @param {number|boolean} progress Progress percent or `false` for indeterminate
17742 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
17743 this.progress
= progress
;
17745 if ( progress
!== false ) {
17746 this.$bar
.css( 'width', this.progress
+ '%' );
17747 this.$element
.attr( 'aria-valuenow', this.progress
);
17749 this.$bar
.css( 'width', '' );
17750 this.$element
.removeAttr( 'aria-valuenow' );
17752 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress
);
17756 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
17757 * and a menu of search results, which is displayed beneath the query
17758 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
17759 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
17760 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
17762 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
17763 * the [OOjs UI demos][1] for an example.
17765 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
17768 * @extends OO.ui.Widget
17771 * @param {Object} [config] Configuration options
17772 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
17773 * @cfg {string} [value] Initial query value
17775 OO
.ui
.SearchWidget
= function OoUiSearchWidget( config
) {
17776 // Configuration initialization
17777 config
= config
|| {};
17779 // Parent constructor
17780 OO
.ui
.SearchWidget
.parent
.call( this, config
);
17783 this.query
= new OO
.ui
.TextInputWidget( {
17785 placeholder
: config
.placeholder
,
17786 value
: config
.value
17788 this.results
= new OO
.ui
.SelectWidget();
17789 this.$query
= $( '<div>' );
17790 this.$results
= $( '<div>' );
17793 this.query
.connect( this, {
17794 change
: 'onQueryChange',
17795 enter
: 'onQueryEnter'
17797 this.query
.$input
.on( 'keydown', this.onQueryKeydown
.bind( this ) );
17801 .addClass( 'oo-ui-searchWidget-query' )
17802 .append( this.query
.$element
);
17804 .addClass( 'oo-ui-searchWidget-results' )
17805 .append( this.results
.$element
);
17807 .addClass( 'oo-ui-searchWidget' )
17808 .append( this.$results
, this.$query
);
17813 OO
.inheritClass( OO
.ui
.SearchWidget
, OO
.ui
.Widget
);
17818 * Handle query key down events.
17821 * @param {jQuery.Event} e Key down event
17823 OO
.ui
.SearchWidget
.prototype.onQueryKeydown = function ( e
) {
17824 var highlightedItem
, nextItem
,
17825 dir
= e
.which
=== OO
.ui
.Keys
.DOWN
? 1 : ( e
.which
=== OO
.ui
.Keys
.UP
? -1 : 0 );
17828 highlightedItem
= this.results
.getHighlightedItem();
17829 if ( !highlightedItem
) {
17830 highlightedItem
= this.results
.getSelectedItem();
17832 nextItem
= this.results
.getRelativeSelectableItem( highlightedItem
, dir
);
17833 this.results
.highlightItem( nextItem
);
17834 nextItem
.scrollElementIntoView();
17839 * Handle select widget select events.
17841 * Clears existing results. Subclasses should repopulate items according to new query.
17844 * @param {string} value New value
17846 OO
.ui
.SearchWidget
.prototype.onQueryChange = function () {
17848 this.results
.clearItems();
17852 * Handle select widget enter key events.
17854 * Chooses highlighted item.
17857 * @param {string} value New value
17859 OO
.ui
.SearchWidget
.prototype.onQueryEnter = function () {
17860 var highlightedItem
= this.results
.getHighlightedItem();
17861 if ( highlightedItem
) {
17862 this.results
.chooseItem( highlightedItem
);
17867 * Get the query input.
17869 * @return {OO.ui.TextInputWidget} Query input
17871 OO
.ui
.SearchWidget
.prototype.getQuery = function () {
17876 * Get the search results menu.
17878 * @return {OO.ui.SelectWidget} Menu of search results
17880 OO
.ui
.SearchWidget
.prototype.getResults = function () {
17881 return this.results
;
17885 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
17886 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
17887 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
17890 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
17891 * information, please see the [OOjs UI documentation on MediaWiki][1].
17894 * // Example of a select widget with three options
17895 * var select = new OO.ui.SelectWidget( {
17897 * new OO.ui.OptionWidget( {
17899 * label: 'Option One',
17901 * new OO.ui.OptionWidget( {
17903 * label: 'Option Two',
17905 * new OO.ui.OptionWidget( {
17907 * label: 'Option Three',
17911 * $( 'body' ).append( select.$element );
17913 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17917 * @extends OO.ui.Widget
17918 * @mixins OO.ui.mixin.GroupWidget
17921 * @param {Object} [config] Configuration options
17922 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
17923 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
17924 * the [OOjs UI documentation on MediaWiki] [2] for examples.
17925 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17927 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
17928 // Configuration initialization
17929 config
= config
|| {};
17931 // Parent constructor
17932 OO
.ui
.SelectWidget
.parent
.call( this, config
);
17934 // Mixin constructors
17935 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
17938 this.pressed
= false;
17939 this.selecting
= null;
17940 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
17941 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
17942 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
17943 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
17944 this.keyPressBuffer
= '';
17945 this.keyPressBufferTimer
= null;
17948 this.connect( this, {
17951 this.$element
.on( {
17952 mousedown
: this.onMouseDown
.bind( this ),
17953 mouseover
: this.onMouseOver
.bind( this ),
17954 mouseleave
: this.onMouseLeave
.bind( this )
17959 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
17960 .attr( 'role', 'listbox' );
17961 if ( Array
.isArray( config
.items
) ) {
17962 this.addItems( config
.items
);
17968 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
17970 // Need to mixin base class as well
17971 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupElement
);
17972 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
17975 OO
.ui
.SelectWidget
.static.passAllFilter = function () {
17984 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
17986 * @param {OO.ui.OptionWidget|null} item Highlighted item
17992 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
17993 * pressed state of an option.
17995 * @param {OO.ui.OptionWidget|null} item Pressed item
18001 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
18003 * @param {OO.ui.OptionWidget|null} item Selected item
18008 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
18009 * @param {OO.ui.OptionWidget} item Chosen item
18015 * An `add` event is emitted when options are added to the select with the #addItems method.
18017 * @param {OO.ui.OptionWidget[]} items Added items
18018 * @param {number} index Index of insertion point
18024 * A `remove` event is emitted when options are removed from the select with the #clearItems
18025 * or #removeItems methods.
18027 * @param {OO.ui.OptionWidget[]} items Removed items
18033 * Handle mouse down events.
18036 * @param {jQuery.Event} e Mouse down event
18038 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
18041 if ( !this.isDisabled() && e
.which
=== 1 ) {
18042 this.togglePressed( true );
18043 item
= this.getTargetItem( e
);
18044 if ( item
&& item
.isSelectable() ) {
18045 this.pressItem( item
);
18046 this.selecting
= item
;
18047 OO
.ui
.addCaptureEventListener(
18048 this.getElementDocument(),
18050 this.onMouseUpHandler
18052 OO
.ui
.addCaptureEventListener(
18053 this.getElementDocument(),
18055 this.onMouseMoveHandler
18063 * Handle mouse up events.
18066 * @param {jQuery.Event} e Mouse up event
18068 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
18071 this.togglePressed( false );
18072 if ( !this.selecting
) {
18073 item
= this.getTargetItem( e
);
18074 if ( item
&& item
.isSelectable() ) {
18075 this.selecting
= item
;
18078 if ( !this.isDisabled() && e
.which
=== 1 && this.selecting
) {
18079 this.pressItem( null );
18080 this.chooseItem( this.selecting
);
18081 this.selecting
= null;
18084 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup',
18085 this.onMouseUpHandler
);
18086 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mousemove',
18087 this.onMouseMoveHandler
);
18093 * Handle mouse move events.
18096 * @param {jQuery.Event} e Mouse move event
18098 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
18101 if ( !this.isDisabled() && this.pressed
) {
18102 item
= this.getTargetItem( e
);
18103 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
18104 this.pressItem( item
);
18105 this.selecting
= item
;
18112 * Handle mouse over events.
18115 * @param {jQuery.Event} e Mouse over event
18117 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
18120 if ( !this.isDisabled() ) {
18121 item
= this.getTargetItem( e
);
18122 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
18128 * Handle mouse leave events.
18131 * @param {jQuery.Event} e Mouse over event
18133 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
18134 if ( !this.isDisabled() ) {
18135 this.highlightItem( null );
18141 * Handle key down events.
18144 * @param {jQuery.Event} e Key down event
18146 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
18149 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
18151 if ( !this.isDisabled() && this.isVisible() ) {
18152 switch ( e
.keyCode
) {
18153 case OO
.ui
.Keys
.ENTER
:
18154 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
18155 // Was only highlighted, now let's select it. No-op if already selected.
18156 this.chooseItem( currentItem
);
18160 case OO
.ui
.Keys
.UP
:
18161 case OO
.ui
.Keys
.LEFT
:
18162 this.clearKeyPressBuffer();
18163 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
18166 case OO
.ui
.Keys
.DOWN
:
18167 case OO
.ui
.Keys
.RIGHT
:
18168 this.clearKeyPressBuffer();
18169 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
18172 case OO
.ui
.Keys
.ESCAPE
:
18173 case OO
.ui
.Keys
.TAB
:
18174 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
18175 currentItem
.setHighlighted( false );
18177 this.unbindKeyDownListener();
18178 this.unbindKeyPressListener();
18179 // Don't prevent tabbing away / defocusing
18185 if ( nextItem
.constructor.static.highlightable
) {
18186 this.highlightItem( nextItem
);
18188 this.chooseItem( nextItem
);
18190 nextItem
.scrollElementIntoView();
18194 // Can't just return false, because e is not always a jQuery event
18195 e
.preventDefault();
18196 e
.stopPropagation();
18202 * Bind key down listener.
18206 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
18207 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler
);
18211 * Unbind key down listener.
18215 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
18216 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler
);
18220 * Clear the key-press buffer
18224 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
18225 if ( this.keyPressBufferTimer
) {
18226 clearTimeout( this.keyPressBufferTimer
);
18227 this.keyPressBufferTimer
= null;
18229 this.keyPressBuffer
= '';
18233 * Handle key press events.
18236 * @param {jQuery.Event} e Key press event
18238 OO
.ui
.SelectWidget
.prototype.onKeyPress = function ( e
) {
18239 var c
, filter
, item
;
18241 if ( !e
.charCode
) {
18242 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
18243 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
18248 if ( String
.fromCodePoint
) {
18249 c
= String
.fromCodePoint( e
.charCode
);
18251 c
= String
.fromCharCode( e
.charCode
);
18254 if ( this.keyPressBufferTimer
) {
18255 clearTimeout( this.keyPressBufferTimer
);
18257 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
18259 item
= this.getHighlightedItem() || this.getSelectedItem();
18261 if ( this.keyPressBuffer
=== c
) {
18262 // Common (if weird) special case: typing "xxxx" will cycle through all
18263 // the items beginning with "x".
18265 item
= this.getRelativeSelectableItem( item
, 1 );
18268 this.keyPressBuffer
+= c
;
18271 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
18272 if ( !item
|| !filter( item
) ) {
18273 item
= this.getRelativeSelectableItem( item
, 1, filter
);
18276 if ( item
.constructor.static.highlightable
) {
18277 this.highlightItem( item
);
18279 this.chooseItem( item
);
18281 item
.scrollElementIntoView();
18288 * Get a matcher for the specific string
18291 * @param {string} s String to match against items
18292 * @param {boolean} [exact=false] Only accept exact matches
18293 * @return {Function} function ( OO.ui.OptionItem ) => boolean
18295 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
, exact
) {
18298 if ( s
.normalize
) {
18301 s
= exact
? s
.trim() : s
.replace( /^\s+/, '' );
18302 re
= '^\\s*' + s
.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
18306 re
= new RegExp( re
, 'i' );
18307 return function ( item
) {
18308 var l
= item
.getLabel();
18309 if ( typeof l
!== 'string' ) {
18310 l
= item
.$label
.text();
18312 if ( l
.normalize
) {
18315 return re
.test( l
);
18320 * Bind key press listener.
18324 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
18325 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler
);
18329 * Unbind key down listener.
18331 * If you override this, be sure to call this.clearKeyPressBuffer() from your
18336 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
18337 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler
);
18338 this.clearKeyPressBuffer();
18342 * Visibility change handler
18345 * @param {boolean} visible
18347 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
18349 this.clearKeyPressBuffer();
18354 * Get the closest item to a jQuery.Event.
18357 * @param {jQuery.Event} e
18358 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
18360 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
18361 return $( e
.target
).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
18365 * Get selected item.
18367 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
18369 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
18372 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18373 if ( this.items
[ i
].isSelected() ) {
18374 return this.items
[ i
];
18381 * Get highlighted item.
18383 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
18385 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
18388 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18389 if ( this.items
[ i
].isHighlighted() ) {
18390 return this.items
[ i
];
18397 * Toggle pressed state.
18399 * Press is a state that occurs when a user mouses down on an item, but
18400 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
18401 * until the user releases the mouse.
18403 * @param {boolean} pressed An option is being pressed
18405 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
18406 if ( pressed
=== undefined ) {
18407 pressed
= !this.pressed
;
18409 if ( pressed
!== this.pressed
) {
18411 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
18412 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
18413 this.pressed
= pressed
;
18418 * Highlight an option. If the `item` param is omitted, no options will be highlighted
18419 * and any existing highlight will be removed. The highlight is mutually exclusive.
18421 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
18425 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
18426 var i
, len
, highlighted
,
18429 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18430 highlighted
= this.items
[ i
] === item
;
18431 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
18432 this.items
[ i
].setHighlighted( highlighted
);
18437 this.emit( 'highlight', item
);
18444 * Fetch an item by its label.
18446 * @param {string} label Label of the item to select.
18447 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18448 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
18450 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
18451 var i
, item
, found
,
18452 len
= this.items
.length
,
18453 filter
= this.getItemMatcher( label
, true );
18455 for ( i
= 0; i
< len
; i
++ ) {
18456 item
= this.items
[ i
];
18457 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
18464 filter
= this.getItemMatcher( label
, false );
18465 for ( i
= 0; i
< len
; i
++ ) {
18466 item
= this.items
[ i
];
18467 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
18483 * Programmatically select an option by its label. If the item does not exist,
18484 * all options will be deselected.
18486 * @param {string} [label] Label of the item to select.
18487 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18491 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
18492 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
18493 if ( label
=== undefined || !itemFromLabel
) {
18494 return this.selectItem();
18496 return this.selectItem( itemFromLabel
);
18500 * Programmatically select an option by its data. If the `data` parameter is omitted,
18501 * or if the item does not exist, all options will be deselected.
18503 * @param {Object|string} [data] Value of the item to select, omit to deselect all
18507 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
18508 var itemFromData
= this.getItemFromData( data
);
18509 if ( data
=== undefined || !itemFromData
) {
18510 return this.selectItem();
18512 return this.selectItem( itemFromData
);
18516 * Programmatically select an option by its reference. If the `item` parameter is omitted,
18517 * all options will be deselected.
18519 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
18523 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
18524 var i
, len
, selected
,
18527 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18528 selected
= this.items
[ i
] === item
;
18529 if ( this.items
[ i
].isSelected() !== selected
) {
18530 this.items
[ i
].setSelected( selected
);
18535 this.emit( 'select', item
);
18544 * Press is a state that occurs when a user mouses down on an item, but has not
18545 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
18546 * releases the mouse.
18548 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
18552 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
18553 var i
, len
, pressed
,
18556 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18557 pressed
= this.items
[ i
] === item
;
18558 if ( this.items
[ i
].isPressed() !== pressed
) {
18559 this.items
[ i
].setPressed( pressed
);
18564 this.emit( 'press', item
);
18573 * Note that ‘choose’ should never be modified programmatically. A user can choose
18574 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
18575 * use the #selectItem method.
18577 * This method is identical to #selectItem, but may vary in subclasses that take additional action
18578 * when users choose an item with the keyboard or mouse.
18580 * @param {OO.ui.OptionWidget} item Item to choose
18584 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
18586 this.selectItem( item
);
18587 this.emit( 'choose', item
);
18594 * Get an option by its position relative to the specified item (or to the start of the option array,
18595 * if item is `null`). The direction in which to search through the option array is specified with a
18596 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
18597 * `null` if there are no options in the array.
18599 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
18600 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
18601 * @param {Function} filter Only consider items for which this function returns
18602 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
18603 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
18605 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
, filter
) {
18606 var currentIndex
, nextIndex
, i
,
18607 increase
= direction
> 0 ? 1 : -1,
18608 len
= this.items
.length
;
18610 if ( !$.isFunction( filter
) ) {
18611 filter
= OO
.ui
.SelectWidget
.static.passAllFilter
;
18614 if ( item
instanceof OO
.ui
.OptionWidget
) {
18615 currentIndex
= this.items
.indexOf( item
);
18616 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
18618 // If no item is selected and moving forward, start at the beginning.
18619 // If moving backward, start at the end.
18620 nextIndex
= direction
> 0 ? 0 : len
- 1;
18623 for ( i
= 0; i
< len
; i
++ ) {
18624 item
= this.items
[ nextIndex
];
18625 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
18628 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
18634 * Get the next selectable item or `null` if there are no selectable items.
18635 * Disabled options and menu-section markers and breaks are not selectable.
18637 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
18639 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
18642 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18643 item
= this.items
[ i
];
18644 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() ) {
18653 * Add an array of options to the select. Optionally, an index number can be used to
18654 * specify an insertion point.
18656 * @param {OO.ui.OptionWidget[]} items Items to add
18657 * @param {number} [index] Index to insert items after
18661 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
18663 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
18665 // Always provide an index, even if it was omitted
18666 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
18672 * Remove the specified array of options from the select. Options will be detached
18673 * from the DOM, not removed, so they can be reused later. To remove all options from
18674 * the select, you may wish to use the #clearItems method instead.
18676 * @param {OO.ui.OptionWidget[]} items Items to remove
18680 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
18683 // Deselect items being removed
18684 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
18686 if ( item
.isSelected() ) {
18687 this.selectItem( null );
18692 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
18694 this.emit( 'remove', items
);
18700 * Clear all options from the select. Options will be detached from the DOM, not removed,
18701 * so that they can be reused later. To remove a subset of options from the select, use
18702 * the #removeItems method.
18707 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
18708 var items
= this.items
.slice();
18711 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
18714 this.selectItem( null );
18716 this.emit( 'remove', items
);
18722 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
18723 * button options and is used together with
18724 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
18725 * highlighting, choosing, and selecting mutually exclusive options. Please see
18726 * the [OOjs UI documentation on MediaWiki] [1] for more information.
18729 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
18730 * var option1 = new OO.ui.ButtonOptionWidget( {
18732 * label: 'Option 1',
18733 * title: 'Button option 1'
18736 * var option2 = new OO.ui.ButtonOptionWidget( {
18738 * label: 'Option 2',
18739 * title: 'Button option 2'
18742 * var option3 = new OO.ui.ButtonOptionWidget( {
18744 * label: 'Option 3',
18745 * title: 'Button option 3'
18748 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
18749 * items: [ option1, option2, option3 ]
18751 * $( 'body' ).append( buttonSelect.$element );
18753 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18756 * @extends OO.ui.SelectWidget
18757 * @mixins OO.ui.mixin.TabIndexedElement
18760 * @param {Object} [config] Configuration options
18762 OO
.ui
.ButtonSelectWidget
= function OoUiButtonSelectWidget( config
) {
18763 // Parent constructor
18764 OO
.ui
.ButtonSelectWidget
.parent
.call( this, config
);
18766 // Mixin constructors
18767 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
18770 this.$element
.on( {
18771 focus
: this.bindKeyDownListener
.bind( this ),
18772 blur
: this.unbindKeyDownListener
.bind( this )
18776 this.$element
.addClass( 'oo-ui-buttonSelectWidget' );
18781 OO
.inheritClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.SelectWidget
);
18782 OO
.mixinClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
18785 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
18786 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
18787 * an interface for adding, removing and selecting options.
18788 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18790 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
18791 * OO.ui.RadioSelectInputWidget instead.
18794 * // A RadioSelectWidget with RadioOptions.
18795 * var option1 = new OO.ui.RadioOptionWidget( {
18797 * label: 'Selected radio option'
18800 * var option2 = new OO.ui.RadioOptionWidget( {
18802 * label: 'Unselected radio option'
18805 * var radioSelect=new OO.ui.RadioSelectWidget( {
18806 * items: [ option1, option2 ]
18809 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
18810 * radioSelect.selectItem( option1 );
18812 * $( 'body' ).append( radioSelect.$element );
18814 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18818 * @extends OO.ui.SelectWidget
18819 * @mixins OO.ui.mixin.TabIndexedElement
18822 * @param {Object} [config] Configuration options
18824 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
18825 // Parent constructor
18826 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
18828 // Mixin constructors
18829 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
18832 this.$element
.on( {
18833 focus
: this.bindKeyDownListener
.bind( this ),
18834 blur
: this.unbindKeyDownListener
.bind( this )
18839 .addClass( 'oo-ui-radioSelectWidget' )
18840 .attr( 'role', 'radiogroup' );
18845 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
18846 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
18849 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
18850 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
18851 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
18852 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
18853 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
18854 * and customized to be opened, closed, and displayed as needed.
18856 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
18857 * mouse outside the menu.
18859 * Menus also have support for keyboard interaction:
18861 * - Enter/Return key: choose and select a menu option
18862 * - Up-arrow key: highlight the previous menu option
18863 * - Down-arrow key: highlight the next menu option
18864 * - Esc key: hide the menu
18866 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18867 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18870 * @extends OO.ui.SelectWidget
18871 * @mixins OO.ui.mixin.ClippableElement
18874 * @param {Object} [config] Configuration options
18875 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
18876 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
18877 * and {@link OO.ui.mixin.LookupElement LookupElement}
18878 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
18879 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiSelectWidget CapsuleMultiSelectWidget}
18880 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
18881 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
18882 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
18883 * that button, unless the button (or its parent widget) is passed in here.
18884 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
18885 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
18887 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
18888 // Configuration initialization
18889 config
= config
|| {};
18891 // Parent constructor
18892 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
18894 // Mixin constructors
18895 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
18898 this.newItems
= null;
18899 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
18900 this.filterFromInput
= !!config
.filterFromInput
;
18901 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
18902 this.$widget
= config
.widget
? config
.widget
.$element
: null;
18903 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
18904 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
18908 .addClass( 'oo-ui-menuSelectWidget' )
18909 .attr( 'role', 'menu' );
18911 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
18912 // that reference properties not initialized at that time of parent class construction
18913 // TODO: Find a better way to handle post-constructor setup
18914 this.visible
= false;
18915 this.$element
.addClass( 'oo-ui-element-hidden' );
18920 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
18921 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
18926 * Handles document mouse down events.
18929 * @param {jQuery.Event} e Key down event
18931 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
18933 !OO
.ui
.contains( this.$element
[ 0 ], e
.target
, true ) &&
18934 ( !this.$widget
|| !OO
.ui
.contains( this.$widget
[ 0 ], e
.target
, true ) )
18936 this.toggle( false );
18943 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
18944 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
18946 if ( !this.isDisabled() && this.isVisible() ) {
18947 switch ( e
.keyCode
) {
18948 case OO
.ui
.Keys
.LEFT
:
18949 case OO
.ui
.Keys
.RIGHT
:
18950 // Do nothing if a text field is associated, arrow keys will be handled natively
18951 if ( !this.$input
) {
18952 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
18955 case OO
.ui
.Keys
.ESCAPE
:
18956 case OO
.ui
.Keys
.TAB
:
18957 if ( currentItem
) {
18958 currentItem
.setHighlighted( false );
18960 this.toggle( false );
18961 // Don't prevent tabbing away, prevent defocusing
18962 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
18963 e
.preventDefault();
18964 e
.stopPropagation();
18968 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
18975 * Update menu item visibility after input changes.
18978 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
18980 len
= this.items
.length
,
18981 showAll
= !this.isVisible(),
18982 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() );
18984 for ( i
= 0; i
< len
; i
++ ) {
18985 item
= this.items
[ i
];
18986 if ( item
instanceof OO
.ui
.OptionWidget
) {
18987 item
.toggle( showAll
|| filter( item
) );
18991 // Reevaluate clipping
18998 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
18999 if ( this.$input
) {
19000 this.$input
.on( 'keydown', this.onKeyDownHandler
);
19002 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyDownListener
.call( this );
19009 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
19010 if ( this.$input
) {
19011 this.$input
.off( 'keydown', this.onKeyDownHandler
);
19013 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyDownListener
.call( this );
19020 OO
.ui
.MenuSelectWidget
.prototype.bindKeyPressListener = function () {
19021 if ( this.$input
) {
19022 if ( this.filterFromInput
) {
19023 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
19026 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyPressListener
.call( this );
19033 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyPressListener = function () {
19034 if ( this.$input
) {
19035 if ( this.filterFromInput
) {
19036 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
19037 this.updateItemVisibility();
19040 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyPressListener
.call( this );
19047 * When a user chooses an item, the menu is closed.
19049 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
19050 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
19051 * @param {OO.ui.OptionWidget} item Item to choose
19054 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
19055 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
19056 this.toggle( false );
19063 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
19067 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
19070 if ( !this.newItems
) {
19071 this.newItems
= [];
19074 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
19076 if ( this.isVisible() ) {
19077 // Defer fitting label until item has been attached
19080 this.newItems
.push( item
);
19084 // Reevaluate clipping
19093 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
19095 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
19097 // Reevaluate clipping
19106 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
19108 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
19110 // Reevaluate clipping
19119 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
19120 var i
, len
, change
;
19122 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
19123 change
= visible
!== this.isVisible();
19126 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
19130 this.bindKeyDownListener();
19131 this.bindKeyPressListener();
19133 if ( this.newItems
&& this.newItems
.length
) {
19134 for ( i
= 0, len
= this.newItems
.length
; i
< len
; i
++ ) {
19135 this.newItems
[ i
].fitLabel();
19137 this.newItems
= null;
19139 this.toggleClipping( true );
19142 if ( this.autoHide
) {
19143 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler
);
19146 this.unbindKeyDownListener();
19147 this.unbindKeyPressListener();
19148 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler
);
19149 this.toggleClipping( false );
19157 * FloatingMenuSelectWidget is a menu that will stick under a specified
19158 * container, even when it is inserted elsewhere in the document (for example,
19159 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
19160 * menu from being clipped too aggresively.
19162 * The menu's position is automatically calculated and maintained when the menu
19163 * is toggled or the window is resized.
19165 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
19168 * @extends OO.ui.MenuSelectWidget
19169 * @mixins OO.ui.mixin.FloatableElement
19172 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
19173 * Deprecated, omit this parameter and specify `$container` instead.
19174 * @param {Object} [config] Configuration options
19175 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
19177 OO
.ui
.FloatingMenuSelectWidget
= function OoUiFloatingMenuSelectWidget( inputWidget
, config
) {
19178 // Allow 'inputWidget' parameter and config for backwards compatibility
19179 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
19180 config
= inputWidget
;
19181 inputWidget
= config
.inputWidget
;
19184 // Configuration initialization
19185 config
= config
|| {};
19187 // Parent constructor
19188 OO
.ui
.FloatingMenuSelectWidget
.parent
.call( this, config
);
19190 // Properties (must be set before mixin constructors)
19191 this.inputWidget
= inputWidget
; // For backwards compatibility
19192 this.$container
= config
.$container
|| this.inputWidget
.$element
;
19194 // Mixins constructors
19195 OO
.ui
.mixin
.FloatableElement
.call( this, $.extend( {}, config
, { $floatableContainer
: this.$container
} ) );
19198 this.$element
.addClass( 'oo-ui-floatingMenuSelectWidget' );
19199 // For backwards compatibility
19200 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
19205 OO
.inheritClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
19206 OO
.mixinClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.mixin
.FloatableElement
);
19208 // For backwards compatibility
19209 OO
.ui
.TextInputMenuSelectWidget
= OO
.ui
.FloatingMenuSelectWidget
;
19216 OO
.ui
.FloatingMenuSelectWidget
.prototype.toggle = function ( visible
) {
19218 visible
= visible
=== undefined ? !this.isVisible() : !!visible
;
19219 change
= visible
!== this.isVisible();
19221 if ( change
&& visible
) {
19222 // Make sure the width is set before the parent method runs.
19223 this.setIdealSize( this.$container
.width() );
19227 // This will call this.clip(), which is nonsensical since we're not positioned yet...
19228 OO
.ui
.FloatingMenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
19231 this.togglePositioning( this.isVisible() );
19238 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
19239 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
19241 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
19244 * @extends OO.ui.SelectWidget
19245 * @mixins OO.ui.mixin.TabIndexedElement
19248 * @param {Object} [config] Configuration options
19250 OO
.ui
.OutlineSelectWidget
= function OoUiOutlineSelectWidget( config
) {
19251 // Parent constructor
19252 OO
.ui
.OutlineSelectWidget
.parent
.call( this, config
);
19254 // Mixin constructors
19255 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
19258 this.$element
.on( {
19259 focus
: this.bindKeyDownListener
.bind( this ),
19260 blur
: this.unbindKeyDownListener
.bind( this )
19264 this.$element
.addClass( 'oo-ui-outlineSelectWidget' );
19269 OO
.inheritClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.SelectWidget
);
19270 OO
.mixinClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
19273 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
19275 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
19278 * @extends OO.ui.SelectWidget
19279 * @mixins OO.ui.mixin.TabIndexedElement
19282 * @param {Object} [config] Configuration options
19284 OO
.ui
.TabSelectWidget
= function OoUiTabSelectWidget( config
) {
19285 // Parent constructor
19286 OO
.ui
.TabSelectWidget
.parent
.call( this, config
);
19288 // Mixin constructors
19289 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
19292 this.$element
.on( {
19293 focus
: this.bindKeyDownListener
.bind( this ),
19294 blur
: this.unbindKeyDownListener
.bind( this )
19298 this.$element
.addClass( 'oo-ui-tabSelectWidget' );
19303 OO
.inheritClass( OO
.ui
.TabSelectWidget
, OO
.ui
.SelectWidget
);
19304 OO
.mixinClass( OO
.ui
.TabSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
19307 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
19308 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
19309 * (to adjust the value in increments) to allow the user to enter a number.
19312 * // Example: A NumberInputWidget.
19313 * var numberInput = new OO.ui.NumberInputWidget( {
19314 * label: 'NumberInputWidget',
19315 * input: { value: 5, min: 1, max: 10 }
19317 * $( 'body' ).append( numberInput.$element );
19320 * @extends OO.ui.Widget
19323 * @param {Object} [config] Configuration options
19324 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
19325 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
19326 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
19327 * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
19328 * @cfg {number} [min=-Infinity] Minimum allowed value
19329 * @cfg {number} [max=Infinity] Maximum allowed value
19330 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
19331 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
19333 OO
.ui
.NumberInputWidget
= function OoUiNumberInputWidget( config
) {
19334 // Configuration initialization
19335 config
= $.extend( {
19343 // Parent constructor
19344 OO
.ui
.NumberInputWidget
.parent
.call( this, config
);
19347 this.input
= new OO
.ui
.TextInputWidget( $.extend(
19349 disabled
: this.isDisabled()
19353 this.minusButton
= new OO
.ui
.ButtonWidget( $.extend(
19355 disabled
: this.isDisabled(),
19358 config
.minusButton
,
19360 classes
: [ 'oo-ui-numberInputWidget-minusButton' ],
19364 this.plusButton
= new OO
.ui
.ButtonWidget( $.extend(
19366 disabled
: this.isDisabled(),
19371 classes
: [ 'oo-ui-numberInputWidget-plusButton' ],
19377 this.input
.connect( this, {
19378 change
: this.emit
.bind( this, 'change' ),
19379 enter
: this.emit
.bind( this, 'enter' )
19381 this.input
.$input
.on( {
19382 keydown
: this.onKeyDown
.bind( this ),
19383 'wheel mousewheel DOMMouseScroll': this.onWheel
.bind( this )
19385 this.plusButton
.connect( this, {
19386 click
: [ 'onButtonClick', +1 ]
19388 this.minusButton
.connect( this, {
19389 click
: [ 'onButtonClick', -1 ]
19393 this.setIsInteger( !!config
.isInteger
);
19394 this.setRange( config
.min
, config
.max
);
19395 this.setStep( config
.step
, config
.pageStep
);
19397 this.$field
= $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
19399 this.minusButton
.$element
,
19400 this.input
.$element
,
19401 this.plusButton
.$element
19403 this.$element
.addClass( 'oo-ui-numberInputWidget' ).append( this.$field
);
19404 this.input
.setValidation( this.validateNumber
.bind( this ) );
19409 OO
.inheritClass( OO
.ui
.NumberInputWidget
, OO
.ui
.Widget
);
19414 * A `change` event is emitted when the value of the input changes.
19420 * An `enter` event is emitted when the user presses 'enter' inside the text box.
19428 * Set whether only integers are allowed
19429 * @param {boolean} flag
19431 OO
.ui
.NumberInputWidget
.prototype.setIsInteger = function ( flag
) {
19432 this.isInteger
= !!flag
;
19433 this.input
.setValidityFlag();
19437 * Get whether only integers are allowed
19438 * @return {boolean} Flag value
19440 OO
.ui
.NumberInputWidget
.prototype.getIsInteger = function () {
19441 return this.isInteger
;
19445 * Set the range of allowed values
19446 * @param {number} min Minimum allowed value
19447 * @param {number} max Maximum allowed value
19449 OO
.ui
.NumberInputWidget
.prototype.setRange = function ( min
, max
) {
19451 throw new Error( 'Minimum (' + min
+ ') must not be greater than maximum (' + max
+ ')' );
19455 this.input
.setValidityFlag();
19459 * Get the current range
19460 * @return {number[]} Minimum and maximum values
19462 OO
.ui
.NumberInputWidget
.prototype.getRange = function () {
19463 return [ this.min
, this.max
];
19467 * Set the stepping deltas
19468 * @param {number} step Normal step
19469 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
19471 OO
.ui
.NumberInputWidget
.prototype.setStep = function ( step
, pageStep
) {
19473 throw new Error( 'Step value must be positive' );
19475 if ( pageStep
=== null ) {
19476 pageStep
= step
* 10;
19477 } else if ( pageStep
<= 0 ) {
19478 throw new Error( 'Page step value must be positive' );
19481 this.pageStep
= pageStep
;
19485 * Get the current stepping values
19486 * @return {number[]} Step and page step
19488 OO
.ui
.NumberInputWidget
.prototype.getStep = function () {
19489 return [ this.step
, this.pageStep
];
19493 * Get the current value of the widget
19496 OO
.ui
.NumberInputWidget
.prototype.getValue = function () {
19497 return this.input
.getValue();
19501 * Get the current value of the widget as a number
19502 * @return {number} May be NaN, or an invalid number
19504 OO
.ui
.NumberInputWidget
.prototype.getNumericValue = function () {
19505 return +this.input
.getValue();
19509 * Set the value of the widget
19510 * @param {string} value Invalid values are allowed
19512 OO
.ui
.NumberInputWidget
.prototype.setValue = function ( value
) {
19513 this.input
.setValue( value
);
19517 * Adjust the value of the widget
19518 * @param {number} delta Adjustment amount
19520 OO
.ui
.NumberInputWidget
.prototype.adjustValue = function ( delta
) {
19521 var n
, v
= this.getNumericValue();
19524 if ( isNaN( delta
) || !isFinite( delta
) ) {
19525 throw new Error( 'Delta must be a finite number' );
19528 if ( isNaN( v
) ) {
19532 n
= Math
.max( Math
.min( n
, this.max
), this.min
);
19533 if ( this.isInteger
) {
19534 n
= Math
.round( n
);
19539 this.setValue( n
);
19546 * @param {string} value Field value
19547 * @return {boolean}
19549 OO
.ui
.NumberInputWidget
.prototype.validateNumber = function ( value
) {
19551 if ( isNaN( n
) || !isFinite( n
) ) {
19555 /*jshint bitwise: false */
19556 if ( this.isInteger
&& ( n
| 0 ) !== n
) {
19559 /*jshint bitwise: true */
19561 if ( n
< this.min
|| n
> this.max
) {
19569 * Handle mouse click events.
19572 * @param {number} dir +1 or -1
19574 OO
.ui
.NumberInputWidget
.prototype.onButtonClick = function ( dir
) {
19575 this.adjustValue( dir
* this.step
);
19579 * Handle mouse wheel events.
19582 * @param {jQuery.Event} event
19584 OO
.ui
.NumberInputWidget
.prototype.onWheel = function ( event
) {
19587 // Standard 'wheel' event
19588 if ( event
.originalEvent
.deltaMode
!== undefined ) {
19589 this.sawWheelEvent
= true;
19591 if ( event
.originalEvent
.deltaY
) {
19592 delta
= -event
.originalEvent
.deltaY
;
19593 } else if ( event
.originalEvent
.deltaX
) {
19594 delta
= event
.originalEvent
.deltaX
;
19597 // Non-standard events
19598 if ( !this.sawWheelEvent
) {
19599 if ( event
.originalEvent
.wheelDeltaX
) {
19600 delta
= -event
.originalEvent
.wheelDeltaX
;
19601 } else if ( event
.originalEvent
.wheelDeltaY
) {
19602 delta
= event
.originalEvent
.wheelDeltaY
;
19603 } else if ( event
.originalEvent
.wheelDelta
) {
19604 delta
= event
.originalEvent
.wheelDelta
;
19605 } else if ( event
.originalEvent
.detail
) {
19606 delta
= -event
.originalEvent
.detail
;
19611 delta
= delta
< 0 ? -1 : 1;
19612 this.adjustValue( delta
* this.step
);
19619 * Handle key down events.
19622 * @param {jQuery.Event} e Key down event
19624 OO
.ui
.NumberInputWidget
.prototype.onKeyDown = function ( e
) {
19625 if ( !this.isDisabled() ) {
19626 switch ( e
.which
) {
19627 case OO
.ui
.Keys
.UP
:
19628 this.adjustValue( this.step
);
19630 case OO
.ui
.Keys
.DOWN
:
19631 this.adjustValue( -this.step
);
19633 case OO
.ui
.Keys
.PAGEUP
:
19634 this.adjustValue( this.pageStep
);
19636 case OO
.ui
.Keys
.PAGEDOWN
:
19637 this.adjustValue( -this.pageStep
);
19646 OO
.ui
.NumberInputWidget
.prototype.setDisabled = function ( disabled
) {
19648 OO
.ui
.NumberInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
19650 if ( this.input
) {
19651 this.input
.setDisabled( this.isDisabled() );
19653 if ( this.minusButton
) {
19654 this.minusButton
.setDisabled( this.isDisabled() );
19656 if ( this.plusButton
) {
19657 this.plusButton
.setDisabled( this.isDisabled() );
19664 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
19665 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
19666 * visually by a slider in the leftmost position.
19669 * // Toggle switches in the 'off' and 'on' position.
19670 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
19671 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
19675 * // Create a FieldsetLayout to layout and label switches
19676 * var fieldset = new OO.ui.FieldsetLayout( {
19677 * label: 'Toggle switches'
19679 * fieldset.addItems( [
19680 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
19681 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
19683 * $( 'body' ).append( fieldset.$element );
19686 * @extends OO.ui.ToggleWidget
19687 * @mixins OO.ui.mixin.TabIndexedElement
19690 * @param {Object} [config] Configuration options
19691 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
19692 * By default, the toggle switch is in the 'off' position.
19694 OO
.ui
.ToggleSwitchWidget
= function OoUiToggleSwitchWidget( config
) {
19695 // Parent constructor
19696 OO
.ui
.ToggleSwitchWidget
.parent
.call( this, config
);
19698 // Mixin constructors
19699 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
19702 this.dragging
= false;
19703 this.dragStart
= null;
19704 this.sliding
= false;
19705 this.$glow
= $( '<span>' );
19706 this.$grip
= $( '<span>' );
19709 this.$element
.on( {
19710 click
: this.onClick
.bind( this ),
19711 keypress
: this.onKeyPress
.bind( this )
19715 this.$glow
.addClass( 'oo-ui-toggleSwitchWidget-glow' );
19716 this.$grip
.addClass( 'oo-ui-toggleSwitchWidget-grip' );
19718 .addClass( 'oo-ui-toggleSwitchWidget' )
19719 .attr( 'role', 'checkbox' )
19720 .append( this.$glow
, this.$grip
);
19725 OO
.inheritClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.ToggleWidget
);
19726 OO
.mixinClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.mixin
.TabIndexedElement
);
19731 * Handle mouse click events.
19734 * @param {jQuery.Event} e Mouse click event
19736 OO
.ui
.ToggleSwitchWidget
.prototype.onClick = function ( e
) {
19737 if ( !this.isDisabled() && e
.which
=== 1 ) {
19738 this.setValue( !this.value
);
19744 * Handle key press events.
19747 * @param {jQuery.Event} e Key press event
19749 OO
.ui
.ToggleSwitchWidget
.prototype.onKeyPress = function ( e
) {
19750 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
19751 this.setValue( !this.value
);