3 * https://www.mediawiki.org/wiki/OOjs_UI
5 * Copyright 2011–2015 OOjs UI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: 2015-11-10T23:32:59Z
16 * Namespace for all classes, static methods and static properties.
53 * Generate a unique ID for element
55 * @return {String} [id]
57 OO
.ui
.generateElementId = function () {
59 return 'oojsui-' + OO
.ui
.elementId
;
63 * Check if an element is focusable.
64 * Inspired from :focusable in jQueryUI v1.11.4 - 2015-04-14
66 * @param {jQuery} element Element to test
69 OO
.ui
.isFocusableElement = function ( $element
) {
71 element
= $element
[ 0 ];
73 // Anything disabled is not focusable
74 if ( element
.disabled
) {
78 // Check if the element is visible
80 // This is quicker than calling $element.is( ':visible' )
81 $.expr
.filters
.visible( element
) &&
82 // Check that all parents are visible
83 !$element
.parents().addBack().filter( function () {
84 return $.css( this, 'visibility' ) === 'hidden';
90 // Check if the element is ContentEditable, which is the string 'true'
91 if ( element
.contentEditable
=== 'true' ) {
95 // Anything with a non-negative numeric tabIndex is focusable.
96 // Use .prop to avoid browser bugs
97 if ( $element
.prop( 'tabIndex' ) >= 0 ) {
101 // Some element types are naturally focusable
102 // (indexOf is much faster than regex in Chrome and about the
103 // same in FF: https://jsperf.com/regex-vs-indexof-array2)
104 nodeName
= element
.nodeName
.toLowerCase();
105 if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName
) !== -1 ) {
109 // Links and areas are focusable if they have an href
110 if ( ( nodeName
=== 'a' || nodeName
=== 'area' ) && $element
.attr( 'href' ) !== undefined ) {
118 * Find a focusable child
120 * @param {jQuery} $container Container to search in
121 * @param {boolean} [backwards] Search backwards
122 * @return {jQuery} Focusable child, an empty jQuery object if none found
124 OO
.ui
.findFocusable = function ( $container
, backwards
) {
125 var $focusable
= $( [] ),
126 // $focusableCandidates is a superset of things that
127 // could get matched by isFocusableElement
128 $focusableCandidates
= $container
129 .find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' );
132 $focusableCandidates
= Array
.prototype.reverse
.call( $focusableCandidates
);
135 $focusableCandidates
.each( function () {
136 var $this = $( this );
137 if ( OO
.ui
.isFocusableElement( $this ) ) {
146 * Get the user's language and any fallback languages.
148 * These language codes are used to localize user interface elements in the user's language.
150 * In environments that provide a localization system, this function should be overridden to
151 * return the user's language(s). The default implementation returns English (en) only.
153 * @return {string[]} Language codes, in descending order of priority
155 OO
.ui
.getUserLanguages = function () {
160 * Get a value in an object keyed by language code.
162 * @param {Object.<string,Mixed>} obj Object keyed by language code
163 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
164 * @param {string} [fallback] Fallback code, used if no matching language can be found
165 * @return {Mixed} Local value
167 OO
.ui
.getLocalValue = function ( obj
, lang
, fallback
) {
170 // Requested language
174 // Known user language
175 langs
= OO
.ui
.getUserLanguages();
176 for ( i
= 0, len
= langs
.length
; i
< len
; i
++ ) {
183 if ( obj
[ fallback
] ) {
184 return obj
[ fallback
];
186 // First existing language
187 for ( lang
in obj
) {
195 * Check if a node is contained within another node
197 * Similar to jQuery#contains except a list of containers can be supplied
198 * and a boolean argument allows you to include the container in the match list
200 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
201 * @param {HTMLElement} contained Node to find
202 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
203 * @return {boolean} The node is in the list of target nodes
205 OO
.ui
.contains = function ( containers
, contained
, matchContainers
) {
207 if ( !Array
.isArray( containers
) ) {
208 containers
= [ containers
];
210 for ( i
= containers
.length
- 1; i
>= 0; i
-- ) {
211 if ( ( matchContainers
&& contained
=== containers
[ i
] ) || $.contains( containers
[ i
], contained
) ) {
219 * Return a function, that, as long as it continues to be invoked, will not
220 * be triggered. The function will be called after it stops being called for
221 * N milliseconds. If `immediate` is passed, trigger the function on the
222 * leading edge, instead of the trailing.
224 * Ported from: http://underscorejs.org/underscore.js
226 * @param {Function} func
227 * @param {number} wait
228 * @param {boolean} immediate
231 OO
.ui
.debounce = function ( func
, wait
, immediate
) {
236 later = function () {
239 func
.apply( context
, args
);
242 if ( immediate
&& !timeout
) {
243 func
.apply( context
, args
);
245 clearTimeout( timeout
);
246 timeout
= setTimeout( later
, wait
);
251 * Proxy for `node.addEventListener( eventName, handler, true )`, if the browser supports it.
252 * Otherwise falls back to non-capturing event listeners.
254 * @param {HTMLElement} node
255 * @param {string} eventName
256 * @param {Function} handler
258 OO
.ui
.addCaptureEventListener = function ( node
, eventName
, handler
) {
259 if ( node
.addEventListener
) {
260 node
.addEventListener( eventName
, handler
, true );
262 node
.attachEvent( 'on' + eventName
, handler
);
267 * Proxy for `node.removeEventListener( eventName, handler, true )`, if the browser supports it.
268 * Otherwise falls back to non-capturing event listeners.
270 * @param {HTMLElement} node
271 * @param {string} eventName
272 * @param {Function} handler
274 OO
.ui
.removeCaptureEventListener = function ( node
, eventName
, handler
) {
275 if ( node
.addEventListener
) {
276 node
.removeEventListener( eventName
, handler
, true );
278 node
.detachEvent( 'on' + eventName
, handler
);
283 * Reconstitute a JavaScript object corresponding to a widget created by
284 * the PHP implementation.
286 * This is an alias for `OO.ui.Element.static.infuse()`.
288 * @param {string|HTMLElement|jQuery} idOrNode
289 * A DOM id (if a string) or node for the widget to infuse.
290 * @return {OO.ui.Element}
291 * The `OO.ui.Element` corresponding to this (infusable) document node.
293 OO
.ui
.infuse = function ( idOrNode
) {
294 return OO
.ui
.Element
.static.infuse( idOrNode
);
299 * Message store for the default implementation of OO.ui.msg
301 * Environments that provide a localization system should not use this, but should override
302 * OO.ui.msg altogether.
307 // Tool tip for a button that moves items in a list down one place
308 'ooui-outline-control-move-down': 'Move item down',
309 // Tool tip for a button that moves items in a list up one place
310 'ooui-outline-control-move-up': 'Move item up',
311 // Tool tip for a button that removes items from a list
312 'ooui-outline-control-remove': 'Remove item',
313 // Label for the toolbar group that contains a list of all other available tools
314 'ooui-toolbar-more': 'More',
315 // Label for the fake tool that expands the full list of tools in a toolbar group
316 'ooui-toolgroup-expand': 'More',
317 // Label for the fake tool that collapses the full list of tools in a toolbar group
318 'ooui-toolgroup-collapse': 'Fewer',
319 // Default label for the accept button of a confirmation dialog
320 'ooui-dialog-message-accept': 'OK',
321 // Default label for the reject button of a confirmation dialog
322 'ooui-dialog-message-reject': 'Cancel',
323 // Title for process dialog error description
324 'ooui-dialog-process-error': 'Something went wrong',
325 // Label for process dialog dismiss error button, visible when describing errors
326 'ooui-dialog-process-dismiss': 'Dismiss',
327 // Label for process dialog retry action button, visible when describing only recoverable errors
328 'ooui-dialog-process-retry': 'Try again',
329 // Label for process dialog retry action button, visible when describing only warnings
330 'ooui-dialog-process-continue': 'Continue',
331 // Label for the file selection widget's select file button
332 'ooui-selectfile-button-select': 'Select a file',
333 // Label for the file selection widget if file selection is not supported
334 'ooui-selectfile-not-supported': 'File selection is not supported',
335 // Label for the file selection widget when no file is currently selected
336 'ooui-selectfile-placeholder': 'No file is selected',
337 // Label for the file selection widget's drop target
338 'ooui-selectfile-dragdrop-placeholder': 'Drop file here'
342 * Get a localized message.
344 * In environments that provide a localization system, this function should be overridden to
345 * return the message translated in the user's language. The default implementation always returns
348 * After the message key, message parameters may optionally be passed. In the default implementation,
349 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
350 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
351 * they support unnamed, ordered message parameters.
354 * @param {string} key Message key
355 * @param {Mixed...} [params] Message parameters
356 * @return {string} Translated message with parameters substituted
358 OO
.ui
.msg = function ( key
) {
359 var message
= messages
[ key
],
360 params
= Array
.prototype.slice
.call( arguments
, 1 );
361 if ( typeof message
=== 'string' ) {
362 // Perform $1 substitution
363 message
= message
.replace( /\$(\d+)/g, function ( unused
, n
) {
364 var i
= parseInt( n
, 10 );
365 return params
[ i
- 1 ] !== undefined ? params
[ i
- 1 ] : '$' + n
;
368 // Return placeholder if message not found
369 message
= '[' + key
+ ']';
375 * Package a message and arguments for deferred resolution.
377 * Use this when you are statically specifying a message and the message may not yet be present.
379 * @param {string} key Message key
380 * @param {Mixed...} [params] Message parameters
381 * @return {Function} Function that returns the resolved message when executed
383 OO
.ui
.deferMsg = function () {
384 var args
= arguments
;
386 return OO
.ui
.msg
.apply( OO
.ui
, args
);
393 * If the message is a function it will be executed, otherwise it will pass through directly.
395 * @param {Function|string} msg Deferred message, or message text
396 * @return {string} Resolved message
398 OO
.ui
.resolveMsg = function ( msg
) {
399 if ( $.isFunction( msg
) ) {
406 * @param {string} url
409 OO
.ui
.isSafeUrl = function ( url
) {
411 // Keep in sync with php/Tag.php
413 'bitcoin:', 'ftp:', 'ftps:', 'geo:', 'git:', 'gopher:', 'http:', 'https:', 'irc:', 'ircs:',
414 'magnet:', 'mailto:', 'mms:', 'news:', 'nntp:', 'redis:', 'sftp:', 'sip:', 'sips:', 'sms:', 'ssh:',
415 'svn:', 'tel:', 'telnet:', 'urn:', 'worldwind:', 'xmpp:'
418 if ( url
.indexOf( ':' ) === -1 ) {
423 protocol
= url
.split( ':', 1 )[ 0 ] + ':';
424 if ( !protocol
.match( /^([A-za-z0-9\+\.\-])+:/ ) ) {
425 // Not a valid protocol, safe
429 // Safe if in the whitelist
430 return whitelist
.indexOf( protocol
) !== -1;
440 * Namespace for OOjs UI mixins.
442 * Mixins are named according to the type of object they are intended to
443 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
444 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
445 * is intended to be mixed in to an instance of OO.ui.Widget.
453 * PendingElement is a mixin that is used to create elements that notify users that something is happening
454 * and that they should wait before proceeding. The pending state is visually represented with a pending
455 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
456 * field of a {@link OO.ui.TextInputWidget text input widget}.
458 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
459 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
460 * in process dialogs.
463 * function MessageDialog( config ) {
464 * MessageDialog.parent.call( this, config );
466 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
468 * MessageDialog.static.actions = [
469 * { action: 'save', label: 'Done', flags: 'primary' },
470 * { label: 'Cancel', flags: 'safe' }
473 * MessageDialog.prototype.initialize = function () {
474 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
475 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
476 * this.content.$element.append( '<p>Click the \'Done\' action widget to see its pending state. Note that action widgets can be marked pending in message dialogs but not process dialogs.</p>' );
477 * this.$body.append( this.content.$element );
479 * MessageDialog.prototype.getBodyHeight = function () {
482 * MessageDialog.prototype.getActionProcess = function ( action ) {
484 * if ( action === 'save' ) {
485 * dialog.getActions().get({actions: 'save'})[0].pushPending();
486 * return new OO.ui.Process()
488 * .next( function () {
489 * dialog.getActions().get({actions: 'save'})[0].popPending();
492 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
495 * var windowManager = new OO.ui.WindowManager();
496 * $( 'body' ).append( windowManager.$element );
498 * var dialog = new MessageDialog();
499 * windowManager.addWindows( [ dialog ] );
500 * windowManager.openWindow( dialog );
506 * @param {Object} [config] Configuration options
507 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
509 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
510 // Configuration initialization
511 config
= config
|| {};
515 this.$pending
= null;
518 this.setPendingElement( config
.$pending
|| this.$element
);
523 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
528 * Set the pending element (and clean up any existing one).
530 * @param {jQuery} $pending The element to set to pending.
532 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
533 if ( this.$pending
) {
534 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
537 this.$pending
= $pending
;
538 if ( this.pending
> 0 ) {
539 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
544 * Check if an element is pending.
546 * @return {boolean} Element is pending
548 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
549 return !!this.pending
;
553 * Increase the pending counter. The pending state will remain active until the counter is zero
554 * (i.e., the number of calls to #pushPending and #popPending is the same).
558 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
559 if ( this.pending
=== 0 ) {
560 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
561 this.updateThemeClasses();
569 * Decrease the pending counter. The pending state will remain active until the counter is zero
570 * (i.e., the number of calls to #pushPending and #popPending is the same).
574 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
575 if ( this.pending
=== 1 ) {
576 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
577 this.updateThemeClasses();
579 this.pending
= Math
.max( 0, this.pending
- 1 );
585 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
586 * Actions can be made available for specific contexts (modes) and circumstances
587 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
589 * ActionSets contain two types of actions:
591 * - Special: Special actions are the first visible actions with special flags, such as 'safe' and 'primary', the default special flags. Additional special flags can be configured in subclasses with the static #specialFlags property.
592 * - Other: Other actions include all non-special visible actions.
594 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
597 * // Example: An action set used in a process dialog
598 * function MyProcessDialog( config ) {
599 * MyProcessDialog.parent.call( this, config );
601 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
602 * MyProcessDialog.static.title = 'An action set in a process dialog';
603 * // An action set that uses modes ('edit' and 'help' mode, in this example).
604 * MyProcessDialog.static.actions = [
605 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
606 * { action: 'help', modes: 'edit', label: 'Help' },
607 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
608 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
611 * MyProcessDialog.prototype.initialize = function () {
612 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
613 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
614 * this.panel1.$element.append( '<p>This dialog uses an action set (continue, help, cancel, back) configured with modes. This is edit mode. Click \'help\' to see help mode.</p>' );
615 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
616 * this.panel2.$element.append( '<p>This is help mode. Only the \'back\' action widget is configured to be visible here. Click \'back\' to return to \'edit\' mode.</p>' );
617 * this.stackLayout = new OO.ui.StackLayout( {
618 * items: [ this.panel1, this.panel2 ]
620 * this.$body.append( this.stackLayout.$element );
622 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
623 * return MyProcessDialog.parent.prototype.getSetupProcess.call( this, data )
624 * .next( function () {
625 * this.actions.setMode( 'edit' );
628 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
629 * if ( action === 'help' ) {
630 * this.actions.setMode( 'help' );
631 * this.stackLayout.setItem( this.panel2 );
632 * } else if ( action === 'back' ) {
633 * this.actions.setMode( 'edit' );
634 * this.stackLayout.setItem( this.panel1 );
635 * } else if ( action === 'continue' ) {
637 * return new OO.ui.Process( function () {
641 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
643 * MyProcessDialog.prototype.getBodyHeight = function () {
644 * return this.panel1.$element.outerHeight( true );
646 * var windowManager = new OO.ui.WindowManager();
647 * $( 'body' ).append( windowManager.$element );
648 * var dialog = new MyProcessDialog( {
651 * windowManager.addWindows( [ dialog ] );
652 * windowManager.openWindow( dialog );
654 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
658 * @mixins OO.EventEmitter
661 * @param {Object} [config] Configuration options
663 OO
.ui
.ActionSet
= function OoUiActionSet( config
) {
664 // Configuration initialization
665 config
= config
|| {};
667 // Mixin constructors
668 OO
.EventEmitter
.call( this );
673 actions
: 'getAction',
677 this.categorized
= {};
680 this.organized
= false;
681 this.changing
= false;
682 this.changed
= false;
687 OO
.mixinClass( OO
.ui
.ActionSet
, OO
.EventEmitter
);
689 /* Static Properties */
692 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
693 * header of a {@link OO.ui.ProcessDialog process dialog}.
694 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
696 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
703 OO
.ui
.ActionSet
.static.specialFlags
= [ 'safe', 'primary' ];
710 * A 'click' event is emitted when an action is clicked.
712 * @param {OO.ui.ActionWidget} action Action that was clicked
718 * A 'resize' event is emitted when an action widget is resized.
720 * @param {OO.ui.ActionWidget} action Action that was resized
726 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
728 * @param {OO.ui.ActionWidget[]} added Actions added
734 * A 'remove' event is emitted when actions are {@link #method-remove removed}
735 * or {@link #clear cleared}.
737 * @param {OO.ui.ActionWidget[]} added Actions removed
743 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
744 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
751 * Handle action change events.
756 OO
.ui
.ActionSet
.prototype.onActionChange = function () {
757 this.organized
= false;
758 if ( this.changing
) {
761 this.emit( 'change' );
766 * Check if an action is one of the special actions.
768 * @param {OO.ui.ActionWidget} action Action to check
769 * @return {boolean} Action is special
771 OO
.ui
.ActionSet
.prototype.isSpecial = function ( action
) {
774 for ( flag
in this.special
) {
775 if ( action
=== this.special
[ flag
] ) {
784 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
787 * @param {Object} [filters] Filters to use, omit to get all actions
788 * @param {string|string[]} [filters.actions] Actions that action widgets must have
789 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
790 * @param {string|string[]} [filters.modes] Modes that action widgets must have
791 * @param {boolean} [filters.visible] Action widgets must be visible
792 * @param {boolean} [filters.disabled] Action widgets must be disabled
793 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
795 OO
.ui
.ActionSet
.prototype.get = function ( filters
) {
796 var i
, len
, list
, category
, actions
, index
, match
, matches
;
801 // Collect category candidates
803 for ( category
in this.categorized
) {
804 list
= filters
[ category
];
806 if ( !Array
.isArray( list
) ) {
809 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
810 actions
= this.categorized
[ category
][ list
[ i
] ];
811 if ( Array
.isArray( actions
) ) {
812 matches
.push
.apply( matches
, actions
);
817 // Remove by boolean filters
818 for ( i
= 0, len
= matches
.length
; i
< len
; i
++ ) {
819 match
= matches
[ i
];
821 ( filters
.visible
!== undefined && match
.isVisible() !== filters
.visible
) ||
822 ( filters
.disabled
!== undefined && match
.isDisabled() !== filters
.disabled
)
824 matches
.splice( i
, 1 );
830 for ( i
= 0, len
= matches
.length
; i
< len
; i
++ ) {
831 match
= matches
[ i
];
832 index
= matches
.lastIndexOf( match
);
833 while ( index
!== i
) {
834 matches
.splice( index
, 1 );
836 index
= matches
.lastIndexOf( match
);
841 return this.list
.slice();
845 * Get 'special' actions.
847 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
848 * Special flags can be configured in subclasses by changing the static #specialFlags property.
850 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
852 OO
.ui
.ActionSet
.prototype.getSpecial = function () {
854 return $.extend( {}, this.special
);
858 * Get 'other' actions.
860 * Other actions include all non-special visible action widgets.
862 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
864 OO
.ui
.ActionSet
.prototype.getOthers = function () {
866 return this.others
.slice();
870 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
871 * to be available in the specified mode will be made visible. All other actions will be hidden.
873 * @param {string} mode The mode. Only actions configured to be available in the specified
874 * mode will be made visible.
879 OO
.ui
.ActionSet
.prototype.setMode = function ( mode
) {
882 this.changing
= true;
883 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
884 action
= this.list
[ i
];
885 action
.toggle( action
.hasMode( mode
) );
888 this.organized
= false;
889 this.changing
= false;
890 this.emit( 'change' );
896 * Set the abilities of the specified actions.
898 * Action widgets that are configured with the specified actions will be enabled
899 * or disabled based on the boolean values specified in the `actions`
902 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
903 * values that indicate whether or not the action should be enabled.
906 OO
.ui
.ActionSet
.prototype.setAbilities = function ( actions
) {
907 var i
, len
, action
, item
;
909 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
910 item
= this.list
[ i
];
911 action
= item
.getAction();
912 if ( actions
[ action
] !== undefined ) {
913 item
.setDisabled( !actions
[ action
] );
921 * Executes a function once per action.
923 * When making changes to multiple actions, use this method instead of iterating over the actions
924 * manually to defer emitting a #change event until after all actions have been changed.
926 * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get
927 * @param {Function} callback Callback to run for each action; callback is invoked with three
928 * arguments: the action, the action's index, the list of actions being iterated over
931 OO
.ui
.ActionSet
.prototype.forEach = function ( filter
, callback
) {
932 this.changed
= false;
933 this.changing
= true;
934 this.get( filter
).forEach( callback
);
935 this.changing
= false;
936 if ( this.changed
) {
937 this.emit( 'change' );
944 * Add action widgets to the action set.
946 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
951 OO
.ui
.ActionSet
.prototype.add = function ( actions
) {
954 this.changing
= true;
955 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
956 action
= actions
[ i
];
957 action
.connect( this, {
958 click
: [ 'emit', 'click', action
],
959 resize
: [ 'emit', 'resize', action
],
960 toggle
: [ 'onActionChange' ]
962 this.list
.push( action
);
964 this.organized
= false;
965 this.emit( 'add', actions
);
966 this.changing
= false;
967 this.emit( 'change' );
973 * Remove action widgets from the set.
975 * To remove all actions, you may wish to use the #clear method instead.
977 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
982 OO
.ui
.ActionSet
.prototype.remove = function ( actions
) {
983 var i
, len
, index
, action
;
985 this.changing
= true;
986 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
987 action
= actions
[ i
];
988 index
= this.list
.indexOf( action
);
989 if ( index
!== -1 ) {
990 action
.disconnect( this );
991 this.list
.splice( index
, 1 );
994 this.organized
= false;
995 this.emit( 'remove', actions
);
996 this.changing
= false;
997 this.emit( 'change' );
1003 * Remove all action widets from the set.
1005 * To remove only specified actions, use the {@link #method-remove remove} method instead.
1011 OO
.ui
.ActionSet
.prototype.clear = function () {
1013 removed
= this.list
.slice();
1015 this.changing
= true;
1016 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
1017 action
= this.list
[ i
];
1018 action
.disconnect( this );
1023 this.organized
= false;
1024 this.emit( 'remove', removed
);
1025 this.changing
= false;
1026 this.emit( 'change' );
1034 * This is called whenever organized information is requested. It will only reorganize the actions
1035 * if something has changed since the last time it ran.
1040 OO
.ui
.ActionSet
.prototype.organize = function () {
1041 var i
, iLen
, j
, jLen
, flag
, action
, category
, list
, item
, special
,
1042 specialFlags
= this.constructor.static.specialFlags
;
1044 if ( !this.organized
) {
1045 this.categorized
= {};
1048 for ( i
= 0, iLen
= this.list
.length
; i
< iLen
; i
++ ) {
1049 action
= this.list
[ i
];
1050 if ( action
.isVisible() ) {
1051 // Populate categories
1052 for ( category
in this.categories
) {
1053 if ( !this.categorized
[ category
] ) {
1054 this.categorized
[ category
] = {};
1056 list
= action
[ this.categories
[ category
] ]();
1057 if ( !Array
.isArray( list
) ) {
1060 for ( j
= 0, jLen
= list
.length
; j
< jLen
; j
++ ) {
1062 if ( !this.categorized
[ category
][ item
] ) {
1063 this.categorized
[ category
][ item
] = [];
1065 this.categorized
[ category
][ item
].push( action
);
1068 // Populate special/others
1070 for ( j
= 0, jLen
= specialFlags
.length
; j
< jLen
; j
++ ) {
1071 flag
= specialFlags
[ j
];
1072 if ( !this.special
[ flag
] && action
.hasFlag( flag
) ) {
1073 this.special
[ flag
] = action
;
1079 this.others
.push( action
);
1083 this.organized
= true;
1090 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
1091 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
1092 * connected to them and can't be interacted with.
1098 * @param {Object} [config] Configuration options
1099 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
1100 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
1102 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
1103 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
1104 * @cfg {string} [text] Text to insert
1105 * @cfg {Array} [content] An array of content elements to append (after #text).
1106 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
1107 * Instances of OO.ui.Element will have their $element appended.
1108 * @cfg {jQuery} [$content] Content elements to append (after #text).
1109 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
1110 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
1111 * Data can also be specified with the #setData method.
1113 OO
.ui
.Element
= function OoUiElement( config
) {
1114 // Configuration initialization
1115 config
= config
|| {};
1119 this.visible
= true;
1120 this.data
= config
.data
;
1121 this.$element
= config
.$element
||
1122 $( document
.createElement( this.getTagName() ) );
1123 this.elementGroup
= null;
1124 this.debouncedUpdateThemeClassesHandler
= OO
.ui
.debounce( this.debouncedUpdateThemeClasses
);
1127 if ( Array
.isArray( config
.classes
) ) {
1128 this.$element
.addClass( config
.classes
.join( ' ' ) );
1131 this.$element
.attr( 'id', config
.id
);
1133 if ( config
.text
) {
1134 this.$element
.text( config
.text
);
1136 if ( config
.content
) {
1137 // The `content` property treats plain strings as text; use an
1138 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
1139 // appropriate $element appended.
1140 this.$element
.append( config
.content
.map( function ( v
) {
1141 if ( typeof v
=== 'string' ) {
1142 // Escape string so it is properly represented in HTML.
1143 return document
.createTextNode( v
);
1144 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
1146 return v
.toString();
1147 } else if ( v
instanceof OO
.ui
.Element
) {
1153 if ( config
.$content
) {
1154 // The `$content` property treats plain strings as HTML.
1155 this.$element
.append( config
.$content
);
1161 OO
.initClass( OO
.ui
.Element
);
1163 /* Static Properties */
1166 * The name of the HTML tag used by the element.
1168 * The static value may be ignored if the #getTagName method is overridden.
1172 * @property {string}
1174 OO
.ui
.Element
.static.tagName
= 'div';
1176 /* Static Methods */
1179 * Reconstitute a JavaScript object corresponding to a widget created
1180 * by the PHP implementation.
1182 * @param {string|HTMLElement|jQuery} idOrNode
1183 * A DOM id (if a string) or node for the widget to infuse.
1184 * @return {OO.ui.Element}
1185 * The `OO.ui.Element` corresponding to this (infusable) document node.
1186 * For `Tag` objects emitted on the HTML side (used occasionally for content)
1187 * the value returned is a newly-created Element wrapping around the existing
1190 OO
.ui
.Element
.static.infuse = function ( idOrNode
) {
1191 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, false );
1192 // Verify that the type matches up.
1193 // FIXME: uncomment after T89721 is fixed (see T90929)
1195 if ( !( obj instanceof this['class'] ) ) {
1196 throw new Error( 'Infusion type mismatch!' );
1203 * Implementation helper for `infuse`; skips the type check and has an
1204 * extra property so that only the top-level invocation touches the DOM.
1206 * @param {string|HTMLElement|jQuery} idOrNode
1207 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
1208 * when the top-level widget of this infusion is inserted into DOM,
1209 * replacing the original node; or false for top-level invocation.
1210 * @return {OO.ui.Element}
1212 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, domPromise
) {
1213 // look for a cached result of a previous infusion.
1214 var id
, $elem
, data
, cls
, parts
, parent
, obj
, top
, state
;
1215 if ( typeof idOrNode
=== 'string' ) {
1217 $elem
= $( document
.getElementById( id
) );
1219 $elem
= $( idOrNode
);
1220 id
= $elem
.attr( 'id' );
1222 if ( !$elem
.length
) {
1223 throw new Error( 'Widget not found: ' + id
);
1225 data
= $elem
.data( 'ooui-infused' ) || $elem
[ 0 ].oouiInfused
;
1228 if ( data
=== true ) {
1229 throw new Error( 'Circular dependency! ' + id
);
1233 data
= $elem
.attr( 'data-ooui' );
1235 throw new Error( 'No infusion data found: ' + id
);
1238 data
= $.parseJSON( data
);
1242 if ( !( data
&& data
._
) ) {
1243 throw new Error( 'No valid infusion data found: ' + id
);
1245 if ( data
._
=== 'Tag' ) {
1246 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
1247 return new OO
.ui
.Element( { $element
: $elem
} );
1249 parts
= data
._
.split( '.' );
1250 cls
= OO
.getProp
.apply( OO
, [ window
].concat( parts
) );
1251 if ( cls
=== undefined ) {
1252 // The PHP output might be old and not including the "OO.ui" prefix
1253 // TODO: Remove this back-compat after next major release
1254 cls
= OO
.getProp
.apply( OO
, [ OO
.ui
].concat( parts
) );
1255 if ( cls
=== undefined ) {
1256 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
1260 // Verify that we're creating an OO.ui.Element instance
1261 parent
= cls
.parent
;
1263 while ( parent
!== undefined ) {
1264 if ( parent
=== OO
.ui
.Element
) {
1269 parent
= parent
.parent
;
1272 if ( parent
!== OO
.ui
.Element
) {
1273 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
1276 if ( domPromise
=== false ) {
1278 domPromise
= top
.promise();
1280 $elem
.data( 'ooui-infused', true ); // prevent loops
1281 data
.id
= id
; // implicit
1282 data
= OO
.copy( data
, null, function deserialize( value
) {
1283 if ( OO
.isPlainObject( value
) ) {
1285 return OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, domPromise
);
1288 return new OO
.ui
.HtmlSnippet( value
.html
);
1292 // allow widgets to reuse parts of the DOM
1293 data
= cls
.static.reusePreInfuseDOM( $elem
[ 0 ], data
);
1294 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
1295 state
= cls
.static.gatherPreInfuseState( $elem
[ 0 ], data
);
1297 // jscs:disable requireCapitalizedConstructors
1298 obj
= new cls( data
);
1299 // jscs:enable requireCapitalizedConstructors
1300 // now replace old DOM with this new DOM.
1302 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
1303 // so only mutate the DOM if we need to.
1304 if ( $elem
[ 0 ] !== obj
.$element
[ 0 ] ) {
1305 $elem
.replaceWith( obj
.$element
);
1306 // This element is now gone from the DOM, but if anyone is holding a reference to it,
1307 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
1308 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
1309 $elem
[ 0 ].oouiInfused
= obj
;
1313 obj
.$element
.data( 'ooui-infused', obj
);
1314 // set the 'data-ooui' attribute so we can identify infused widgets
1315 obj
.$element
.attr( 'data-ooui', '' );
1316 // restore dynamic state after the new element is inserted into DOM
1317 domPromise
.done( obj
.restorePreInfuseState
.bind( obj
, state
) );
1322 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
1324 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
1325 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
1326 * constructor, which will be given the enhanced config.
1329 * @param {HTMLElement} node
1330 * @param {Object} config
1333 OO
.ui
.Element
.static.reusePreInfuseDOM = function ( node
, config
) {
1338 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of a HTML DOM node
1339 * (and its children) that represent an Element of the same class and the given configuration,
1340 * generated by the PHP implementation.
1342 * This method is called just before `node` is detached from the DOM. The return value of this
1343 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
1344 * is inserted into DOM to replace `node`.
1347 * @param {HTMLElement} node
1348 * @param {Object} config
1351 OO
.ui
.Element
.static.gatherPreInfuseState = function () {
1356 * Get a jQuery function within a specific document.
1359 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1360 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1362 * @return {Function} Bound jQuery function
1364 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
1365 function wrapper( selector
) {
1366 return $( selector
, wrapper
.context
);
1369 wrapper
.context
= this.getDocument( context
);
1372 wrapper
.$iframe
= $iframe
;
1379 * Get the document of an element.
1382 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1383 * @return {HTMLDocument|null} Document object
1385 OO
.ui
.Element
.static.getDocument = function ( obj
) {
1386 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1387 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
1388 // Empty jQuery selections might have a context
1391 obj
.ownerDocument
||
1395 ( obj
.nodeType
=== 9 && obj
) ||
1400 * Get the window of an element or document.
1403 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1404 * @return {Window} Window object
1406 OO
.ui
.Element
.static.getWindow = function ( obj
) {
1407 var doc
= this.getDocument( obj
);
1409 // Standard Document.defaultView is IE9+
1410 return doc
.parentWindow
|| doc
.defaultView
;
1414 * Get the direction of an element or document.
1417 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1418 * @return {string} Text direction, either 'ltr' or 'rtl'
1420 OO
.ui
.Element
.static.getDir = function ( obj
) {
1423 if ( obj
instanceof jQuery
) {
1426 isDoc
= obj
.nodeType
=== 9;
1427 isWin
= obj
.document
!== undefined;
1428 if ( isDoc
|| isWin
) {
1434 return $( obj
).css( 'direction' );
1438 * Get the offset between two frames.
1440 * TODO: Make this function not use recursion.
1443 * @param {Window} from Window of the child frame
1444 * @param {Window} [to=window] Window of the parent frame
1445 * @param {Object} [offset] Offset to start with, used internally
1446 * @return {Object} Offset object, containing left and top properties
1448 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
1449 var i
, len
, frames
, frame
, rect
;
1455 offset
= { top
: 0, left
: 0 };
1457 if ( from.parent
=== from ) {
1461 // Get iframe element
1462 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
1463 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
1464 if ( frames
[ i
].contentWindow
=== from ) {
1465 frame
= frames
[ i
];
1470 // Recursively accumulate offset values
1472 rect
= frame
.getBoundingClientRect();
1473 offset
.left
+= rect
.left
;
1474 offset
.top
+= rect
.top
;
1475 if ( from !== to
) {
1476 this.getFrameOffset( from.parent
, offset
);
1483 * Get the offset between two elements.
1485 * The two elements may be in a different frame, but in that case the frame $element is in must
1486 * be contained in the frame $anchor is in.
1489 * @param {jQuery} $element Element whose position to get
1490 * @param {jQuery} $anchor Element to get $element's position relative to
1491 * @return {Object} Translated position coordinates, containing top and left properties
1493 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
1494 var iframe
, iframePos
,
1495 pos
= $element
.offset(),
1496 anchorPos
= $anchor
.offset(),
1497 elementDocument
= this.getDocument( $element
),
1498 anchorDocument
= this.getDocument( $anchor
);
1500 // If $element isn't in the same document as $anchor, traverse up
1501 while ( elementDocument
!== anchorDocument
) {
1502 iframe
= elementDocument
.defaultView
.frameElement
;
1504 throw new Error( '$element frame is not contained in $anchor frame' );
1506 iframePos
= $( iframe
).offset();
1507 pos
.left
+= iframePos
.left
;
1508 pos
.top
+= iframePos
.top
;
1509 elementDocument
= iframe
.ownerDocument
;
1511 pos
.left
-= anchorPos
.left
;
1512 pos
.top
-= anchorPos
.top
;
1517 * Get element border sizes.
1520 * @param {HTMLElement} el Element to measure
1521 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1523 OO
.ui
.Element
.static.getBorders = function ( el
) {
1524 var doc
= el
.ownerDocument
,
1526 // Standard Document.defaultView is IE9+
1527 win
= doc
.parentWindow
|| doc
.defaultView
,
1528 style
= win
&& win
.getComputedStyle
?
1529 win
.getComputedStyle( el
, null ) :
1531 // Standard getComputedStyle() is IE9+
1534 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
1535 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
1536 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
1537 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
1548 * Get dimensions of an element or window.
1551 * @param {HTMLElement|Window} el Element to measure
1552 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1554 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1556 doc
= el
.ownerDocument
|| el
.document
,
1558 // Standard Document.defaultView is IE9+
1559 win
= doc
.parentWindow
|| doc
.defaultView
;
1561 if ( win
=== el
|| el
=== doc
.documentElement
) {
1564 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1566 top
: $win
.scrollTop(),
1567 left
: $win
.scrollLeft()
1569 scrollbar
: { right
: 0, bottom
: 0 },
1573 bottom
: $win
.innerHeight(),
1574 right
: $win
.innerWidth()
1580 borders
: this.getBorders( el
),
1582 top
: $el
.scrollTop(),
1583 left
: $el
.scrollLeft()
1586 right
: $el
.innerWidth() - el
.clientWidth
,
1587 bottom
: $el
.innerHeight() - el
.clientHeight
1589 rect
: el
.getBoundingClientRect()
1595 * Get scrollable object parent
1597 * documentElement can't be used to get or set the scrollTop
1598 * property on Blink. Changing and testing its value lets us
1599 * use 'body' or 'documentElement' based on what is working.
1601 * https://code.google.com/p/chromium/issues/detail?id=303131
1604 * @param {HTMLElement} el Element to find scrollable parent for
1605 * @return {HTMLElement} Scrollable parent
1607 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1608 var scrollTop
, body
;
1610 if ( OO
.ui
.scrollableElement
=== undefined ) {
1611 body
= el
.ownerDocument
.body
;
1612 scrollTop
= body
.scrollTop
;
1615 if ( body
.scrollTop
=== 1 ) {
1616 body
.scrollTop
= scrollTop
;
1617 OO
.ui
.scrollableElement
= 'body';
1619 OO
.ui
.scrollableElement
= 'documentElement';
1623 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1627 * Get closest scrollable container.
1629 * Traverses up until either a scrollable element or the root is reached, in which case the window
1633 * @param {HTMLElement} el Element to find scrollable container for
1634 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1635 * @return {HTMLElement} Closest scrollable container
1637 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1639 // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
1640 props
= [ 'overflow-x', 'overflow-y' ],
1641 $parent
= $( el
).parent();
1643 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1644 props
= [ 'overflow-' + dimension
];
1647 while ( $parent
.length
) {
1648 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1649 return $parent
[ 0 ];
1653 val
= $parent
.css( props
[ i
] );
1654 if ( val
=== 'auto' || val
=== 'scroll' ) {
1655 return $parent
[ 0 ];
1658 $parent
= $parent
.parent();
1660 return this.getDocument( el
).body
;
1664 * Scroll element into view.
1667 * @param {HTMLElement} el Element to scroll into view
1668 * @param {Object} [config] Configuration options
1669 * @param {string} [config.duration] jQuery animation duration value
1670 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1671 * to scroll in both directions
1672 * @param {Function} [config.complete] Function to call when scrolling completes
1674 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1675 var rel
, anim
, callback
, sc
, $sc
, eld
, scd
, $win
;
1677 // Configuration initialization
1678 config
= config
|| {};
1681 callback
= typeof config
.complete
=== 'function' && config
.complete
;
1682 sc
= this.getClosestScrollableContainer( el
, config
.direction
);
1684 eld
= this.getDimensions( el
);
1685 scd
= this.getDimensions( sc
);
1686 $win
= $( this.getWindow( el
) );
1688 // Compute the distances between the edges of el and the edges of the scroll viewport
1689 if ( $sc
.is( 'html, body' ) ) {
1690 // If the scrollable container is the root, this is easy
1693 bottom
: $win
.innerHeight() - eld
.rect
.bottom
,
1694 left
: eld
.rect
.left
,
1695 right
: $win
.innerWidth() - eld
.rect
.right
1698 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1700 top
: eld
.rect
.top
- ( scd
.rect
.top
+ scd
.borders
.top
),
1701 bottom
: scd
.rect
.bottom
- scd
.borders
.bottom
- scd
.scrollbar
.bottom
- eld
.rect
.bottom
,
1702 left
: eld
.rect
.left
- ( scd
.rect
.left
+ scd
.borders
.left
),
1703 right
: scd
.rect
.right
- scd
.borders
.right
- scd
.scrollbar
.right
- eld
.rect
.right
1707 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1708 if ( rel
.top
< 0 ) {
1709 anim
.scrollTop
= scd
.scroll
.top
+ rel
.top
;
1710 } else if ( rel
.top
> 0 && rel
.bottom
< 0 ) {
1711 anim
.scrollTop
= scd
.scroll
.top
+ Math
.min( rel
.top
, -rel
.bottom
);
1714 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1715 if ( rel
.left
< 0 ) {
1716 anim
.scrollLeft
= scd
.scroll
.left
+ rel
.left
;
1717 } else if ( rel
.left
> 0 && rel
.right
< 0 ) {
1718 anim
.scrollLeft
= scd
.scroll
.left
+ Math
.min( rel
.left
, -rel
.right
);
1721 if ( !$.isEmptyObject( anim
) ) {
1722 $sc
.stop( true ).animate( anim
, config
.duration
|| 'fast' );
1724 $sc
.queue( function ( next
) {
1737 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1738 * and reserve space for them, because it probably doesn't.
1740 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1741 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1742 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1743 * and then reattach (or show) them back.
1746 * @param {HTMLElement} el Element to reconsider the scrollbars on
1748 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1749 var i
, len
, scrollLeft
, scrollTop
, nodes
= [];
1750 // Save scroll position
1751 scrollLeft
= el
.scrollLeft
;
1752 scrollTop
= el
.scrollTop
;
1753 // Detach all children
1754 while ( el
.firstChild
) {
1755 nodes
.push( el
.firstChild
);
1756 el
.removeChild( el
.firstChild
);
1759 void el
.offsetHeight
;
1760 // Reattach all children
1761 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1762 el
.appendChild( nodes
[ i
] );
1764 // Restore scroll position (no-op if scrollbars disappeared)
1765 el
.scrollLeft
= scrollLeft
;
1766 el
.scrollTop
= scrollTop
;
1772 * Toggle visibility of an element.
1774 * @param {boolean} [show] Make element visible, omit to toggle visibility
1778 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1779 show
= show
=== undefined ? !this.visible
: !!show
;
1781 if ( show
!== this.isVisible() ) {
1782 this.visible
= show
;
1783 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1784 this.emit( 'toggle', show
);
1791 * Check if element is visible.
1793 * @return {boolean} element is visible
1795 OO
.ui
.Element
.prototype.isVisible = function () {
1796 return this.visible
;
1802 * @return {Mixed} Element data
1804 OO
.ui
.Element
.prototype.getData = function () {
1811 * @param {Mixed} Element data
1814 OO
.ui
.Element
.prototype.setData = function ( data
) {
1820 * Check if element supports one or more methods.
1822 * @param {string|string[]} methods Method or list of methods to check
1823 * @return {boolean} All methods are supported
1825 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1829 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1830 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1831 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1836 return methods
.length
=== support
;
1840 * Update the theme-provided classes.
1842 * @localdoc This is called in element mixins and widget classes any time state changes.
1843 * Updating is debounced, minimizing overhead of changing multiple attributes and
1844 * guaranteeing that theme updates do not occur within an element's constructor
1846 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1847 this.debouncedUpdateThemeClassesHandler();
1852 * @localdoc This method is called directly from the QUnit tests instead of #updateThemeClasses, to
1853 * make them synchronous.
1855 OO
.ui
.Element
.prototype.debouncedUpdateThemeClasses = function () {
1856 OO
.ui
.theme
.updateElementClasses( this );
1860 * Get the HTML tag name.
1862 * Override this method to base the result on instance information.
1864 * @return {string} HTML tag name
1866 OO
.ui
.Element
.prototype.getTagName = function () {
1867 return this.constructor.static.tagName
;
1871 * Check if the element is attached to the DOM
1872 * @return {boolean} The element is attached to the DOM
1874 OO
.ui
.Element
.prototype.isElementAttached = function () {
1875 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1879 * Get the DOM document.
1881 * @return {HTMLDocument} Document object
1883 OO
.ui
.Element
.prototype.getElementDocument = function () {
1884 // Don't cache this in other ways either because subclasses could can change this.$element
1885 return OO
.ui
.Element
.static.getDocument( this.$element
);
1889 * Get the DOM window.
1891 * @return {Window} Window object
1893 OO
.ui
.Element
.prototype.getElementWindow = function () {
1894 return OO
.ui
.Element
.static.getWindow( this.$element
);
1898 * Get closest scrollable container.
1900 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1901 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1905 * Get group element is in.
1907 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1909 OO
.ui
.Element
.prototype.getElementGroup = function () {
1910 return this.elementGroup
;
1914 * Set group element is in.
1916 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1919 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1920 this.elementGroup
= group
;
1925 * Scroll element into view.
1927 * @param {Object} [config] Configuration options
1929 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1930 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1934 * Restore the pre-infusion dynamic state for this widget.
1936 * This method is called after #$element has been inserted into DOM. The parameter is the return
1937 * value of #gatherPreInfuseState.
1940 * @param {Object} state
1942 OO
.ui
.Element
.prototype.restorePreInfuseState = function () {
1946 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1947 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1948 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1949 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1950 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1954 * @extends OO.ui.Element
1955 * @mixins OO.EventEmitter
1958 * @param {Object} [config] Configuration options
1960 OO
.ui
.Layout
= function OoUiLayout( config
) {
1961 // Configuration initialization
1962 config
= config
|| {};
1964 // Parent constructor
1965 OO
.ui
.Layout
.parent
.call( this, config
);
1967 // Mixin constructors
1968 OO
.EventEmitter
.call( this );
1971 this.$element
.addClass( 'oo-ui-layout' );
1976 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1977 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1980 * Widgets are compositions of one or more OOjs UI elements that users can both view
1981 * and interact with. All widgets can be configured and modified via a standard API,
1982 * and their state can change dynamically according to a model.
1986 * @extends OO.ui.Element
1987 * @mixins OO.EventEmitter
1990 * @param {Object} [config] Configuration options
1991 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1992 * appearance reflects this state.
1994 OO
.ui
.Widget
= function OoUiWidget( config
) {
1995 // Initialize config
1996 config
= $.extend( { disabled
: false }, config
);
1998 // Parent constructor
1999 OO
.ui
.Widget
.parent
.call( this, config
);
2001 // Mixin constructors
2002 OO
.EventEmitter
.call( this );
2005 this.disabled
= null;
2006 this.wasDisabled
= null;
2009 this.$element
.addClass( 'oo-ui-widget' );
2010 this.setDisabled( !!config
.disabled
);
2015 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
2016 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
2018 /* Static Properties */
2021 * Whether this widget will behave reasonably when wrapped in a HTML `<label>`. If this is true,
2022 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
2027 * @property {boolean}
2029 OO
.ui
.Widget
.static.supportsSimpleLabel
= false;
2036 * A 'disable' event is emitted when the disabled state of the widget changes
2037 * (i.e. on disable **and** enable).
2039 * @param {boolean} disabled Widget is disabled
2045 * A 'toggle' event is emitted when the visibility of the widget changes.
2047 * @param {boolean} visible Widget is visible
2053 * Check if the widget is disabled.
2055 * @return {boolean} Widget is disabled
2057 OO
.ui
.Widget
.prototype.isDisabled = function () {
2058 return this.disabled
;
2062 * Set the 'disabled' state of the widget.
2064 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
2066 * @param {boolean} disabled Disable widget
2069 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
2072 this.disabled
= !!disabled
;
2073 isDisabled
= this.isDisabled();
2074 if ( isDisabled
!== this.wasDisabled
) {
2075 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
2076 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
2077 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
2078 this.emit( 'disable', isDisabled
);
2079 this.updateThemeClasses();
2081 this.wasDisabled
= isDisabled
;
2087 * Update the disabled state, in case of changes in parent widget.
2091 OO
.ui
.Widget
.prototype.updateDisabled = function () {
2092 this.setDisabled( this.disabled
);
2097 * A window is a container for elements that are in a child frame. They are used with
2098 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
2099 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
2100 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
2101 * the window manager will choose a sensible fallback.
2103 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
2104 * different processes are executed:
2106 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
2107 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
2110 * - {@link #getSetupProcess} method is called and its result executed
2111 * - {@link #getReadyProcess} method is called and its result executed
2113 * **opened**: The window is now open
2115 * **closing**: The closing stage begins when the window manager's
2116 * {@link OO.ui.WindowManager#closeWindow closeWindow}
2117 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
2119 * - {@link #getHoldProcess} method is called and its result executed
2120 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
2122 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
2123 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
2124 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
2125 * processing can complete. Always assume window processes are executed asynchronously.
2127 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2129 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
2133 * @extends OO.ui.Element
2134 * @mixins OO.EventEmitter
2137 * @param {Object} [config] Configuration options
2138 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
2139 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
2141 OO
.ui
.Window
= function OoUiWindow( config
) {
2142 // Configuration initialization
2143 config
= config
|| {};
2145 // Parent constructor
2146 OO
.ui
.Window
.parent
.call( this, config
);
2148 // Mixin constructors
2149 OO
.EventEmitter
.call( this );
2152 this.manager
= null;
2153 this.size
= config
.size
|| this.constructor.static.size
;
2154 this.$frame
= $( '<div>' );
2155 this.$overlay
= $( '<div>' );
2156 this.$content
= $( '<div>' );
2158 this.$focusTrapBefore
= $( '<div>' ).prop( 'tabIndex', 0 );
2159 this.$focusTrapAfter
= $( '<div>' ).prop( 'tabIndex', 0 );
2160 this.$focusTraps
= this.$focusTrapBefore
.add( this.$focusTrapAfter
);
2163 this.$overlay
.addClass( 'oo-ui-window-overlay' );
2165 .addClass( 'oo-ui-window-content' )
2166 .attr( 'tabindex', 0 );
2168 .addClass( 'oo-ui-window-frame' )
2169 .append( this.$focusTrapBefore
, this.$content
, this.$focusTrapAfter
);
2172 .addClass( 'oo-ui-window' )
2173 .append( this.$frame
, this.$overlay
);
2175 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
2176 // that reference properties not initialized at that time of parent class construction
2177 // TODO: Find a better way to handle post-constructor setup
2178 this.visible
= false;
2179 this.$element
.addClass( 'oo-ui-element-hidden' );
2184 OO
.inheritClass( OO
.ui
.Window
, OO
.ui
.Element
);
2185 OO
.mixinClass( OO
.ui
.Window
, OO
.EventEmitter
);
2187 /* Static Properties */
2190 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
2192 * The static size is used if no #size is configured during construction.
2196 * @property {string}
2198 OO
.ui
.Window
.static.size
= 'medium';
2203 * Handle mouse down events.
2206 * @param {jQuery.Event} e Mouse down event
2208 OO
.ui
.Window
.prototype.onMouseDown = function ( e
) {
2209 // Prevent clicking on the click-block from stealing focus
2210 if ( e
.target
=== this.$element
[ 0 ] ) {
2216 * Check if the window has been initialized.
2218 * Initialization occurs when a window is added to a manager.
2220 * @return {boolean} Window has been initialized
2222 OO
.ui
.Window
.prototype.isInitialized = function () {
2223 return !!this.manager
;
2227 * Check if the window is visible.
2229 * @return {boolean} Window is visible
2231 OO
.ui
.Window
.prototype.isVisible = function () {
2232 return this.visible
;
2236 * Check if the window is opening.
2238 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
2241 * @return {boolean} Window is opening
2243 OO
.ui
.Window
.prototype.isOpening = function () {
2244 return this.manager
.isOpening( this );
2248 * Check if the window is closing.
2250 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
2252 * @return {boolean} Window is closing
2254 OO
.ui
.Window
.prototype.isClosing = function () {
2255 return this.manager
.isClosing( this );
2259 * Check if the window is opened.
2261 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
2263 * @return {boolean} Window is opened
2265 OO
.ui
.Window
.prototype.isOpened = function () {
2266 return this.manager
.isOpened( this );
2270 * Get the window manager.
2272 * All windows must be attached to a window manager, which is used to open
2273 * and close the window and control its presentation.
2275 * @return {OO.ui.WindowManager} Manager of window
2277 OO
.ui
.Window
.prototype.getManager = function () {
2278 return this.manager
;
2282 * Get the symbolic name of the window size (e.g., `small` or `medium`).
2284 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
2286 OO
.ui
.Window
.prototype.getSize = function () {
2287 var viewport
= OO
.ui
.Element
.static.getDimensions( this.getElementWindow() ),
2288 sizes
= this.manager
.constructor.static.sizes
,
2291 if ( !sizes
[ size
] ) {
2292 size
= this.manager
.constructor.static.defaultSize
;
2294 if ( size
!== 'full' && viewport
.rect
.right
- viewport
.rect
.left
< sizes
[ size
].width
) {
2302 * Get the size properties associated with the current window size
2304 * @return {Object} Size properties
2306 OO
.ui
.Window
.prototype.getSizeProperties = function () {
2307 return this.manager
.constructor.static.sizes
[ this.getSize() ];
2311 * Disable transitions on window's frame for the duration of the callback function, then enable them
2315 * @param {Function} callback Function to call while transitions are disabled
2317 OO
.ui
.Window
.prototype.withoutSizeTransitions = function ( callback
) {
2318 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2319 // Disable transitions first, otherwise we'll get values from when the window was animating.
2321 styleObj
= this.$frame
[ 0 ].style
;
2322 oldTransition
= styleObj
.transition
|| styleObj
.OTransition
|| styleObj
.MsTransition
||
2323 styleObj
.MozTransition
|| styleObj
.WebkitTransition
;
2324 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
2325 styleObj
.MozTransition
= styleObj
.WebkitTransition
= 'none';
2327 // Force reflow to make sure the style changes done inside callback really are not transitioned
2328 this.$frame
.height();
2329 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
2330 styleObj
.MozTransition
= styleObj
.WebkitTransition
= oldTransition
;
2334 * Get the height of the full window contents (i.e., the window head, body and foot together).
2336 * What consistitutes the head, body, and foot varies depending on the window type.
2337 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
2338 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
2339 * and special actions in the head, and dialog content in the body.
2341 * To get just the height of the dialog body, use the #getBodyHeight method.
2343 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
2345 OO
.ui
.Window
.prototype.getContentHeight = function () {
2348 bodyStyleObj
= this.$body
[ 0 ].style
,
2349 frameStyleObj
= this.$frame
[ 0 ].style
;
2351 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2352 // Disable transitions first, otherwise we'll get values from when the window was animating.
2353 this.withoutSizeTransitions( function () {
2354 var oldHeight
= frameStyleObj
.height
,
2355 oldPosition
= bodyStyleObj
.position
;
2356 frameStyleObj
.height
= '1px';
2357 // Force body to resize to new width
2358 bodyStyleObj
.position
= 'relative';
2359 bodyHeight
= win
.getBodyHeight();
2360 frameStyleObj
.height
= oldHeight
;
2361 bodyStyleObj
.position
= oldPosition
;
2365 // Add buffer for border
2366 ( this.$frame
.outerHeight() - this.$frame
.innerHeight() ) +
2367 // Use combined heights of children
2368 ( this.$head
.outerHeight( true ) + bodyHeight
+ this.$foot
.outerHeight( true ) )
2373 * Get the height of the window body.
2375 * To get the height of the full window contents (the window body, head, and foot together),
2376 * use #getContentHeight.
2378 * When this function is called, the window will temporarily have been resized
2379 * to height=1px, so .scrollHeight measurements can be taken accurately.
2381 * @return {number} Height of the window body in pixels
2383 OO
.ui
.Window
.prototype.getBodyHeight = function () {
2384 return this.$body
[ 0 ].scrollHeight
;
2388 * Get the directionality of the frame (right-to-left or left-to-right).
2390 * @return {string} Directionality: `'ltr'` or `'rtl'`
2392 OO
.ui
.Window
.prototype.getDir = function () {
2393 return OO
.ui
.Element
.static.getDir( this.$content
) || 'ltr';
2397 * Get the 'setup' process.
2399 * The setup process is used to set up a window for use in a particular context,
2400 * based on the `data` argument. This method is called during the opening phase of the window’s
2403 * Override this method to add additional steps to the ‘setup’ process the parent method provides
2404 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2407 * To add window content that persists between openings, you may wish to use the #initialize method
2411 * @param {Object} [data] Window opening data
2412 * @return {OO.ui.Process} Setup process
2414 OO
.ui
.Window
.prototype.getSetupProcess = function () {
2415 return new OO
.ui
.Process();
2419 * Get the ‘ready’ process.
2421 * The ready process is used to ready a window for use in a particular
2422 * context, based on the `data` argument. This method is called during the opening phase of
2423 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2425 * Override this method to add additional steps to the ‘ready’ process the parent method
2426 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2427 * methods of OO.ui.Process.
2430 * @param {Object} [data] Window opening data
2431 * @return {OO.ui.Process} Ready process
2433 OO
.ui
.Window
.prototype.getReadyProcess = function () {
2434 return new OO
.ui
.Process();
2438 * Get the 'hold' process.
2440 * The hold proccess is used to keep a window from being used in a particular context,
2441 * based on the `data` argument. This method is called during the closing phase of the window’s
2444 * Override this method to add additional steps to the 'hold' process the parent method provides
2445 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2449 * @param {Object} [data] Window closing data
2450 * @return {OO.ui.Process} Hold process
2452 OO
.ui
.Window
.prototype.getHoldProcess = function () {
2453 return new OO
.ui
.Process();
2457 * Get the ‘teardown’ process.
2459 * The teardown process is used to teardown a window after use. During teardown,
2460 * user interactions within the window are conveyed and the window is closed, based on the `data`
2461 * argument. This method is called during the closing phase of the window’s lifecycle.
2463 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2464 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2468 * @param {Object} [data] Window closing data
2469 * @return {OO.ui.Process} Teardown process
2471 OO
.ui
.Window
.prototype.getTeardownProcess = function () {
2472 return new OO
.ui
.Process();
2476 * Set the window manager.
2478 * This will cause the window to initialize. Calling it more than once will cause an error.
2480 * @param {OO.ui.WindowManager} manager Manager for this window
2481 * @throws {Error} An error is thrown if the method is called more than once
2484 OO
.ui
.Window
.prototype.setManager = function ( manager
) {
2485 if ( this.manager
) {
2486 throw new Error( 'Cannot set window manager, window already has a manager' );
2489 this.manager
= manager
;
2496 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2498 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2502 OO
.ui
.Window
.prototype.setSize = function ( size
) {
2509 * Update the window size.
2511 * @throws {Error} An error is thrown if the window is not attached to a window manager
2514 OO
.ui
.Window
.prototype.updateSize = function () {
2515 if ( !this.manager
) {
2516 throw new Error( 'Cannot update window size, must be attached to a manager' );
2519 this.manager
.updateWindowSize( this );
2525 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2526 * when the window is opening. In general, setDimensions should not be called directly.
2528 * To set the size of the window, use the #setSize method.
2530 * @param {Object} dim CSS dimension properties
2531 * @param {string|number} [dim.width] Width
2532 * @param {string|number} [dim.minWidth] Minimum width
2533 * @param {string|number} [dim.maxWidth] Maximum width
2534 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2535 * @param {string|number} [dim.minWidth] Minimum height
2536 * @param {string|number} [dim.maxWidth] Maximum height
2539 OO
.ui
.Window
.prototype.setDimensions = function ( dim
) {
2542 styleObj
= this.$frame
[ 0 ].style
;
2544 // Calculate the height we need to set using the correct width
2545 if ( dim
.height
=== undefined ) {
2546 this.withoutSizeTransitions( function () {
2547 var oldWidth
= styleObj
.width
;
2548 win
.$frame
.css( 'width', dim
.width
|| '' );
2549 height
= win
.getContentHeight();
2550 styleObj
.width
= oldWidth
;
2553 height
= dim
.height
;
2557 width
: dim
.width
|| '',
2558 minWidth
: dim
.minWidth
|| '',
2559 maxWidth
: dim
.maxWidth
|| '',
2560 height
: height
|| '',
2561 minHeight
: dim
.minHeight
|| '',
2562 maxHeight
: dim
.maxHeight
|| ''
2569 * Initialize window contents.
2571 * Before the window is opened for the first time, #initialize is called so that content that
2572 * persists between openings can be added to the window.
2574 * To set up a window with new content each time the window opens, use #getSetupProcess.
2576 * @throws {Error} An error is thrown if the window is not attached to a window manager
2579 OO
.ui
.Window
.prototype.initialize = function () {
2580 if ( !this.manager
) {
2581 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2585 this.$head
= $( '<div>' );
2586 this.$body
= $( '<div>' );
2587 this.$foot
= $( '<div>' );
2588 this.$document
= $( this.getElementDocument() );
2591 this.$element
.on( 'mousedown', this.onMouseDown
.bind( this ) );
2594 this.$head
.addClass( 'oo-ui-window-head' );
2595 this.$body
.addClass( 'oo-ui-window-body' );
2596 this.$foot
.addClass( 'oo-ui-window-foot' );
2597 this.$content
.append( this.$head
, this.$body
, this.$foot
);
2603 * Called when someone tries to focus the hidden element at the end of the dialog.
2604 * Sends focus back to the start of the dialog.
2606 * @param {jQuery.Event} event Focus event
2608 OO
.ui
.Window
.prototype.onFocusTrapFocused = function ( event
) {
2609 if ( this.$focusTrapBefore
.is( event
.target
) ) {
2610 OO
.ui
.findFocusable( this.$content
, true ).focus();
2612 // this.$content is the part of the focus cycle, and is the first focusable element
2613 this.$content
.focus();
2620 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2621 * method, which returns a promise resolved when the window is done opening.
2623 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2625 * @param {Object} [data] Window opening data
2626 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2627 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2628 * value is a new promise, which is resolved when the window begins closing.
2629 * @throws {Error} An error is thrown if the window is not attached to a window manager
2631 OO
.ui
.Window
.prototype.open = function ( data
) {
2632 if ( !this.manager
) {
2633 throw new Error( 'Cannot open window, must be attached to a manager' );
2636 return this.manager
.openWindow( this, data
);
2642 * This method is a wrapper around a call to the window
2643 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2644 * which returns a closing promise resolved when the window is done closing.
2646 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2647 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2648 * the window closes.
2650 * @param {Object} [data] Window closing data
2651 * @return {jQuery.Promise} Promise resolved when window is closed
2652 * @throws {Error} An error is thrown if the window is not attached to a window manager
2654 OO
.ui
.Window
.prototype.close = function ( data
) {
2655 if ( !this.manager
) {
2656 throw new Error( 'Cannot close window, must be attached to a manager' );
2659 return this.manager
.closeWindow( this, data
);
2665 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2668 * @param {Object} [data] Window opening data
2669 * @return {jQuery.Promise} Promise resolved when window is setup
2671 OO
.ui
.Window
.prototype.setup = function ( data
) {
2673 deferred
= $.Deferred();
2675 this.toggle( true );
2677 this.focusTrapHandler
= OO
.ui
.bind( this.onFocusTrapFocused
, this );
2678 this.$focusTraps
.on( 'focus', this.focusTrapHandler
);
2680 this.getSetupProcess( data
).execute().done( function () {
2681 // Force redraw by asking the browser to measure the elements' widths
2682 win
.$element
.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2683 win
.$content
.addClass( 'oo-ui-window-content-setup' ).width();
2687 return deferred
.promise();
2693 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2696 * @param {Object} [data] Window opening data
2697 * @return {jQuery.Promise} Promise resolved when window is ready
2699 OO
.ui
.Window
.prototype.ready = function ( data
) {
2701 deferred
= $.Deferred();
2703 this.$content
.focus();
2704 this.getReadyProcess( data
).execute().done( function () {
2705 // Force redraw by asking the browser to measure the elements' widths
2706 win
.$element
.addClass( 'oo-ui-window-ready' ).width();
2707 win
.$content
.addClass( 'oo-ui-window-content-ready' ).width();
2711 return deferred
.promise();
2717 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2720 * @param {Object} [data] Window closing data
2721 * @return {jQuery.Promise} Promise resolved when window is held
2723 OO
.ui
.Window
.prototype.hold = function ( data
) {
2725 deferred
= $.Deferred();
2727 this.getHoldProcess( data
).execute().done( function () {
2728 // Get the focused element within the window's content
2729 var $focus
= win
.$content
.find( OO
.ui
.Element
.static.getDocument( win
.$content
).activeElement
);
2731 // Blur the focused element
2732 if ( $focus
.length
) {
2736 // Force redraw by asking the browser to measure the elements' widths
2737 win
.$element
.removeClass( 'oo-ui-window-ready' ).width();
2738 win
.$content
.removeClass( 'oo-ui-window-content-ready' ).width();
2742 return deferred
.promise();
2748 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2751 * @param {Object} [data] Window closing data
2752 * @return {jQuery.Promise} Promise resolved when window is torn down
2754 OO
.ui
.Window
.prototype.teardown = function ( data
) {
2757 return this.getTeardownProcess( data
).execute()
2758 .done( function () {
2759 // Force redraw by asking the browser to measure the elements' widths
2760 win
.$element
.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2761 win
.$content
.removeClass( 'oo-ui-window-content-setup' ).width();
2762 win
.$focusTraps
.off( 'focus', win
.focusTrapHandler
);
2763 win
.toggle( false );
2768 * The Dialog class serves as the base class for the other types of dialogs.
2769 * Unless extended to include controls, the rendered dialog box is a simple window
2770 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2771 * which opens, closes, and controls the presentation of the window. See the
2772 * [OOjs UI documentation on MediaWiki] [1] for more information.
2775 * // A simple dialog window.
2776 * function MyDialog( config ) {
2777 * MyDialog.parent.call( this, config );
2779 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2780 * MyDialog.prototype.initialize = function () {
2781 * MyDialog.parent.prototype.initialize.call( this );
2782 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2783 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2784 * this.$body.append( this.content.$element );
2786 * MyDialog.prototype.getBodyHeight = function () {
2787 * return this.content.$element.outerHeight( true );
2789 * var myDialog = new MyDialog( {
2792 * // Create and append a window manager, which opens and closes the window.
2793 * var windowManager = new OO.ui.WindowManager();
2794 * $( 'body' ).append( windowManager.$element );
2795 * windowManager.addWindows( [ myDialog ] );
2796 * // Open the window!
2797 * windowManager.openWindow( myDialog );
2799 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2803 * @extends OO.ui.Window
2804 * @mixins OO.ui.mixin.PendingElement
2807 * @param {Object} [config] Configuration options
2809 OO
.ui
.Dialog
= function OoUiDialog( config
) {
2810 // Parent constructor
2811 OO
.ui
.Dialog
.parent
.call( this, config
);
2813 // Mixin constructors
2814 OO
.ui
.mixin
.PendingElement
.call( this );
2817 this.actions
= new OO
.ui
.ActionSet();
2818 this.attachedActions
= [];
2819 this.currentAction
= null;
2820 this.onDialogKeyDownHandler
= this.onDialogKeyDown
.bind( this );
2823 this.actions
.connect( this, {
2824 click
: 'onActionClick',
2825 resize
: 'onActionResize',
2826 change
: 'onActionsChange'
2831 .addClass( 'oo-ui-dialog' )
2832 .attr( 'role', 'dialog' );
2837 OO
.inheritClass( OO
.ui
.Dialog
, OO
.ui
.Window
);
2838 OO
.mixinClass( OO
.ui
.Dialog
, OO
.ui
.mixin
.PendingElement
);
2840 /* Static Properties */
2843 * Symbolic name of dialog.
2845 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2846 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2848 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2853 * @property {string}
2855 OO
.ui
.Dialog
.static.name
= '';
2860 * The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function
2861 * that will produce a Label node or string. The title can also be specified with data passed to the
2862 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2867 * @property {jQuery|string|Function}
2869 OO
.ui
.Dialog
.static.title
= '';
2872 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2874 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2875 * value will be overriden.
2877 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2881 * @property {Object[]}
2883 OO
.ui
.Dialog
.static.actions
= [];
2886 * Close the dialog when the 'Esc' key is pressed.
2891 * @property {boolean}
2893 OO
.ui
.Dialog
.static.escapable
= true;
2898 * Handle frame document key down events.
2901 * @param {jQuery.Event} e Key down event
2903 OO
.ui
.Dialog
.prototype.onDialogKeyDown = function ( e
) {
2904 if ( e
.which
=== OO
.ui
.Keys
.ESCAPE
) {
2907 e
.stopPropagation();
2912 * Handle action resized events.
2915 * @param {OO.ui.ActionWidget} action Action that was resized
2917 OO
.ui
.Dialog
.prototype.onActionResize = function () {
2918 // Override in subclass
2922 * Handle action click events.
2925 * @param {OO.ui.ActionWidget} action Action that was clicked
2927 OO
.ui
.Dialog
.prototype.onActionClick = function ( action
) {
2928 if ( !this.isPending() ) {
2929 this.executeAction( action
.getAction() );
2934 * Handle actions change event.
2938 OO
.ui
.Dialog
.prototype.onActionsChange = function () {
2939 this.detachActions();
2940 if ( !this.isClosing() ) {
2941 this.attachActions();
2946 * Get the set of actions used by the dialog.
2948 * @return {OO.ui.ActionSet}
2950 OO
.ui
.Dialog
.prototype.getActions = function () {
2951 return this.actions
;
2955 * Get a process for taking action.
2957 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2958 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2959 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2962 * @param {string} [action] Symbolic name of action
2963 * @return {OO.ui.Process} Action process
2965 OO
.ui
.Dialog
.prototype.getActionProcess = function ( action
) {
2966 return new OO
.ui
.Process()
2967 .next( function () {
2969 // An empty action always closes the dialog without data, which should always be
2970 // safe and make no changes
2979 * @param {Object} [data] Dialog opening data
2980 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2981 * the {@link #static-title static title}
2982 * @param {Object[]} [data.actions] List of configuration options for each
2983 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2985 OO
.ui
.Dialog
.prototype.getSetupProcess = function ( data
) {
2989 return OO
.ui
.Dialog
.parent
.prototype.getSetupProcess
.call( this, data
)
2990 .next( function () {
2991 var config
= this.constructor.static,
2992 actions
= data
.actions
!== undefined ? data
.actions
: config
.actions
;
2994 this.title
.setLabel(
2995 data
.title
!== undefined ? data
.title
: this.constructor.static.title
2997 this.actions
.add( this.getActionWidgets( actions
) );
2999 if ( this.constructor.static.escapable
) {
3000 this.$element
.on( 'keydown', this.onDialogKeyDownHandler
);
3008 OO
.ui
.Dialog
.prototype.getTeardownProcess = function ( data
) {
3010 return OO
.ui
.Dialog
.parent
.prototype.getTeardownProcess
.call( this, data
)
3011 .first( function () {
3012 if ( this.constructor.static.escapable
) {
3013 this.$element
.off( 'keydown', this.onDialogKeyDownHandler
);
3016 this.actions
.clear();
3017 this.currentAction
= null;
3024 OO
.ui
.Dialog
.prototype.initialize = function () {
3028 OO
.ui
.Dialog
.parent
.prototype.initialize
.call( this );
3030 titleId
= OO
.ui
.generateElementId();
3033 this.title
= new OO
.ui
.LabelWidget( {
3038 this.$content
.addClass( 'oo-ui-dialog-content' );
3039 this.$element
.attr( 'aria-labelledby', titleId
);
3040 this.setPendingElement( this.$head
);
3044 * Get action widgets from a list of configs
3046 * @param {Object[]} actions Action widget configs
3047 * @return {OO.ui.ActionWidget[]} Action widgets
3049 OO
.ui
.Dialog
.prototype.getActionWidgets = function ( actions
) {
3050 var i
, len
, widgets
= [];
3051 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
3053 new OO
.ui
.ActionWidget( actions
[ i
] )
3060 * Attach action actions.
3064 OO
.ui
.Dialog
.prototype.attachActions = function () {
3065 // Remember the list of potentially attached actions
3066 this.attachedActions
= this.actions
.get();
3070 * Detach action actions.
3075 OO
.ui
.Dialog
.prototype.detachActions = function () {
3078 // Detach all actions that may have been previously attached
3079 for ( i
= 0, len
= this.attachedActions
.length
; i
< len
; i
++ ) {
3080 this.attachedActions
[ i
].$element
.detach();
3082 this.attachedActions
= [];
3086 * Execute an action.
3088 * @param {string} action Symbolic name of action to execute
3089 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
3091 OO
.ui
.Dialog
.prototype.executeAction = function ( action
) {
3093 this.currentAction
= action
;
3094 return this.getActionProcess( action
).execute()
3095 .always( this.popPending
.bind( this ) );
3099 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
3100 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
3101 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
3102 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
3103 * pertinent data and reused.
3105 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
3106 * `opened`, and `closing`, which represent the primary stages of the cycle:
3108 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
3109 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
3111 * - an `opening` event is emitted with an `opening` promise
3112 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
3113 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
3114 * window and its result executed
3115 * - a `setup` progress notification is emitted from the `opening` promise
3116 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
3117 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
3118 * window and its result executed
3119 * - a `ready` progress notification is emitted from the `opening` promise
3120 * - the `opening` promise is resolved with an `opened` promise
3122 * **Opened**: the window is now open.
3124 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
3125 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
3126 * to close the window.
3128 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
3129 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
3130 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
3131 * window and its result executed
3132 * - a `hold` progress notification is emitted from the `closing` promise
3133 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
3134 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
3135 * window and its result executed
3136 * - a `teardown` progress notification is emitted from the `closing` promise
3137 * - the `closing` promise is resolved. The window is now closed
3139 * See the [OOjs UI documentation on MediaWiki][1] for more information.
3141 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3144 * @extends OO.ui.Element
3145 * @mixins OO.EventEmitter
3148 * @param {Object} [config] Configuration options
3149 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
3150 * Note that window classes that are instantiated with a factory must have
3151 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
3152 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
3154 OO
.ui
.WindowManager
= function OoUiWindowManager( config
) {
3155 // Configuration initialization
3156 config
= config
|| {};
3158 // Parent constructor
3159 OO
.ui
.WindowManager
.parent
.call( this, config
);
3161 // Mixin constructors
3162 OO
.EventEmitter
.call( this );
3165 this.factory
= config
.factory
;
3166 this.modal
= config
.modal
=== undefined || !!config
.modal
;
3168 this.opening
= null;
3170 this.closing
= null;
3171 this.preparingToOpen
= null;
3172 this.preparingToClose
= null;
3173 this.currentWindow
= null;
3174 this.globalEvents
= false;
3175 this.$ariaHidden
= null;
3176 this.onWindowResizeTimeout
= null;
3177 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
3178 this.afterWindowResizeHandler
= this.afterWindowResize
.bind( this );
3182 .addClass( 'oo-ui-windowManager' )
3183 .toggleClass( 'oo-ui-windowManager-modal', this.modal
);
3188 OO
.inheritClass( OO
.ui
.WindowManager
, OO
.ui
.Element
);
3189 OO
.mixinClass( OO
.ui
.WindowManager
, OO
.EventEmitter
);
3194 * An 'opening' event is emitted when the window begins to be opened.
3197 * @param {OO.ui.Window} win Window that's being opened
3198 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
3199 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
3200 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
3201 * @param {Object} data Window opening data
3205 * A 'closing' event is emitted when the window begins to be closed.
3208 * @param {OO.ui.Window} win Window that's being closed
3209 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
3210 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
3211 * processes are complete. When the `closing` promise is resolved, the first argument of its value
3212 * is the closing data.
3213 * @param {Object} data Window closing data
3217 * A 'resize' event is emitted when a window is resized.
3220 * @param {OO.ui.Window} win Window that was resized
3223 /* Static Properties */
3226 * Map of the symbolic name of each window size and its CSS properties.
3230 * @property {Object}
3232 OO
.ui
.WindowManager
.static.sizes
= {
3246 // These can be non-numeric because they are never used in calculations
3253 * Symbolic name of the default window size.
3255 * The default size is used if the window's requested size is not recognized.
3259 * @property {string}
3261 OO
.ui
.WindowManager
.static.defaultSize
= 'medium';
3266 * Handle window resize events.
3269 * @param {jQuery.Event} e Window resize event
3271 OO
.ui
.WindowManager
.prototype.onWindowResize = function () {
3272 clearTimeout( this.onWindowResizeTimeout
);
3273 this.onWindowResizeTimeout
= setTimeout( this.afterWindowResizeHandler
, 200 );
3277 * Handle window resize events.
3280 * @param {jQuery.Event} e Window resize event
3282 OO
.ui
.WindowManager
.prototype.afterWindowResize = function () {
3283 if ( this.currentWindow
) {
3284 this.updateWindowSize( this.currentWindow
);
3289 * Check if window is opening.
3291 * @return {boolean} Window is opening
3293 OO
.ui
.WindowManager
.prototype.isOpening = function ( win
) {
3294 return win
=== this.currentWindow
&& !!this.opening
&& this.opening
.state() === 'pending';
3298 * Check if window is closing.
3300 * @return {boolean} Window is closing
3302 OO
.ui
.WindowManager
.prototype.isClosing = function ( win
) {
3303 return win
=== this.currentWindow
&& !!this.closing
&& this.closing
.state() === 'pending';
3307 * Check if window is opened.
3309 * @return {boolean} Window is opened
3311 OO
.ui
.WindowManager
.prototype.isOpened = function ( win
) {
3312 return win
=== this.currentWindow
&& !!this.opened
&& this.opened
.state() === 'pending';
3316 * Check if a window is being managed.
3318 * @param {OO.ui.Window} win Window to check
3319 * @return {boolean} Window is being managed
3321 OO
.ui
.WindowManager
.prototype.hasWindow = function ( win
) {
3324 for ( name
in this.windows
) {
3325 if ( this.windows
[ name
] === win
) {
3334 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
3336 * @param {OO.ui.Window} win Window being opened
3337 * @param {Object} [data] Window opening data
3338 * @return {number} Milliseconds to wait
3340 OO
.ui
.WindowManager
.prototype.getSetupDelay = function () {
3345 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
3347 * @param {OO.ui.Window} win Window being opened
3348 * @param {Object} [data] Window opening data
3349 * @return {number} Milliseconds to wait
3351 OO
.ui
.WindowManager
.prototype.getReadyDelay = function () {
3356 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
3358 * @param {OO.ui.Window} win Window being closed
3359 * @param {Object} [data] Window closing data
3360 * @return {number} Milliseconds to wait
3362 OO
.ui
.WindowManager
.prototype.getHoldDelay = function () {
3367 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
3368 * executing the ‘teardown’ process.
3370 * @param {OO.ui.Window} win Window being closed
3371 * @param {Object} [data] Window closing data
3372 * @return {number} Milliseconds to wait
3374 OO
.ui
.WindowManager
.prototype.getTeardownDelay = function () {
3375 return this.modal
? 250 : 0;
3379 * Get a window by its symbolic name.
3381 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
3382 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
3383 * for more information about using factories.
3384 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3386 * @param {string} name Symbolic name of the window
3387 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
3388 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
3389 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
3391 OO
.ui
.WindowManager
.prototype.getWindow = function ( name
) {
3392 var deferred
= $.Deferred(),
3393 win
= this.windows
[ name
];
3395 if ( !( win
instanceof OO
.ui
.Window
) ) {
3396 if ( this.factory
) {
3397 if ( !this.factory
.lookup( name
) ) {
3398 deferred
.reject( new OO
.ui
.Error(
3399 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
3402 win
= this.factory
.create( name
);
3403 this.addWindows( [ win
] );
3404 deferred
.resolve( win
);
3407 deferred
.reject( new OO
.ui
.Error(
3408 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
3412 deferred
.resolve( win
);
3415 return deferred
.promise();
3419 * Get current window.
3421 * @return {OO.ui.Window|null} Currently opening/opened/closing window
3423 OO
.ui
.WindowManager
.prototype.getCurrentWindow = function () {
3424 return this.currentWindow
;
3430 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
3431 * @param {Object} [data] Window opening data
3432 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3433 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3436 OO
.ui
.WindowManager
.prototype.openWindow = function ( win
, data
) {
3438 opening
= $.Deferred();
3440 // Argument handling
3441 if ( typeof win
=== 'string' ) {
3442 return this.getWindow( win
).then( function ( win
) {
3443 return manager
.openWindow( win
, data
);
3448 if ( !this.hasWindow( win
) ) {
3449 opening
.reject( new OO
.ui
.Error(
3450 'Cannot open window: window is not attached to manager'
3452 } else if ( this.preparingToOpen
|| this.opening
|| this.opened
) {
3453 opening
.reject( new OO
.ui
.Error(
3454 'Cannot open window: another window is opening or open'
3459 if ( opening
.state() !== 'rejected' ) {
3460 // If a window is currently closing, wait for it to complete
3461 this.preparingToOpen
= $.when( this.closing
);
3462 // Ensure handlers get called after preparingToOpen is set
3463 this.preparingToOpen
.done( function () {
3464 if ( manager
.modal
) {
3465 manager
.toggleGlobalEvents( true );
3466 manager
.toggleAriaIsolation( true );
3468 manager
.currentWindow
= win
;
3469 manager
.opening
= opening
;
3470 manager
.preparingToOpen
= null;
3471 manager
.emit( 'opening', win
, opening
, data
);
3472 setTimeout( function () {
3473 win
.setup( data
).then( function () {
3474 manager
.updateWindowSize( win
);
3475 manager
.opening
.notify( { state
: 'setup' } );
3476 setTimeout( function () {
3477 win
.ready( data
).then( function () {
3478 manager
.opening
.notify( { state
: 'ready' } );
3479 manager
.opening
= null;
3480 manager
.opened
= $.Deferred();
3481 opening
.resolve( manager
.opened
.promise(), data
);
3483 }, manager
.getReadyDelay() );
3485 }, manager
.getSetupDelay() );
3489 return opening
.promise();
3495 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3496 * @param {Object} [data] Window closing data
3497 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3498 * See {@link #event-closing 'closing' event} for more information about closing promises.
3499 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3502 OO
.ui
.WindowManager
.prototype.closeWindow = function ( win
, data
) {
3504 closing
= $.Deferred(),
3507 // Argument handling
3508 if ( typeof win
=== 'string' ) {
3509 win
= this.windows
[ win
];
3510 } else if ( !this.hasWindow( win
) ) {
3516 closing
.reject( new OO
.ui
.Error(
3517 'Cannot close window: window is not attached to manager'
3519 } else if ( win
!== this.currentWindow
) {
3520 closing
.reject( new OO
.ui
.Error(
3521 'Cannot close window: window already closed with different data'
3523 } else if ( this.preparingToClose
|| this.closing
) {
3524 closing
.reject( new OO
.ui
.Error(
3525 'Cannot close window: window already closing with different data'
3530 if ( closing
.state() !== 'rejected' ) {
3531 // If the window is currently opening, close it when it's done
3532 this.preparingToClose
= $.when( this.opening
);
3533 // Ensure handlers get called after preparingToClose is set
3534 this.preparingToClose
.done( function () {
3535 manager
.closing
= closing
;
3536 manager
.preparingToClose
= null;
3537 manager
.emit( 'closing', win
, closing
, data
);
3538 opened
= manager
.opened
;
3539 manager
.opened
= null;
3540 opened
.resolve( closing
.promise(), data
);
3541 setTimeout( function () {
3542 win
.hold( data
).then( function () {
3543 closing
.notify( { state
: 'hold' } );
3544 setTimeout( function () {
3545 win
.teardown( data
).then( function () {
3546 closing
.notify( { state
: 'teardown' } );
3547 if ( manager
.modal
) {
3548 manager
.toggleGlobalEvents( false );
3549 manager
.toggleAriaIsolation( false );
3551 manager
.closing
= null;
3552 manager
.currentWindow
= null;
3553 closing
.resolve( data
);
3555 }, manager
.getTeardownDelay() );
3557 }, manager
.getHoldDelay() );
3561 return closing
.promise();
3565 * Add windows to the window manager.
3567 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3568 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3569 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3571 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3572 * by reference, symbolic name, or explicitly defined symbolic names.
3573 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3574 * explicit nor a statically configured symbolic name.
3576 OO
.ui
.WindowManager
.prototype.addWindows = function ( windows
) {
3577 var i
, len
, win
, name
, list
;
3579 if ( Array
.isArray( windows
) ) {
3580 // Convert to map of windows by looking up symbolic names from static configuration
3582 for ( i
= 0, len
= windows
.length
; i
< len
; i
++ ) {
3583 name
= windows
[ i
].constructor.static.name
;
3584 if ( typeof name
!== 'string' ) {
3585 throw new Error( 'Cannot add window' );
3587 list
[ name
] = windows
[ i
];
3589 } else if ( OO
.isPlainObject( windows
) ) {
3594 for ( name
in list
) {
3596 this.windows
[ name
] = win
.toggle( false );
3597 this.$element
.append( win
.$element
);
3598 win
.setManager( this );
3603 * Remove the specified windows from the windows manager.
3605 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3606 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3607 * longer listens to events, use the #destroy method.
3609 * @param {string[]} names Symbolic names of windows to remove
3610 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3611 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3613 OO
.ui
.WindowManager
.prototype.removeWindows = function ( names
) {
3614 var i
, len
, win
, name
, cleanupWindow
,
3617 cleanup = function ( name
, win
) {
3618 delete manager
.windows
[ name
];
3619 win
.$element
.detach();
3622 for ( i
= 0, len
= names
.length
; i
< len
; i
++ ) {
3624 win
= this.windows
[ name
];
3626 throw new Error( 'Cannot remove window' );
3628 cleanupWindow
= cleanup
.bind( null, name
, win
);
3629 promises
.push( this.closeWindow( name
).then( cleanupWindow
, cleanupWindow
) );
3632 return $.when
.apply( $, promises
);
3636 * Remove all windows from the window manager.
3638 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3639 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3640 * To remove just a subset of windows, use the #removeWindows method.
3642 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3644 OO
.ui
.WindowManager
.prototype.clearWindows = function () {
3645 return this.removeWindows( Object
.keys( this.windows
) );
3649 * Set dialog size. In general, this method should not be called directly.
3651 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3655 OO
.ui
.WindowManager
.prototype.updateWindowSize = function ( win
) {
3658 // Bypass for non-current, and thus invisible, windows
3659 if ( win
!== this.currentWindow
) {
3663 isFullscreen
= win
.getSize() === 'full';
3665 this.$element
.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen
);
3666 this.$element
.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen
);
3667 win
.setDimensions( win
.getSizeProperties() );
3669 this.emit( 'resize', win
);
3675 * Bind or unbind global events for scrolling.
3678 * @param {boolean} [on] Bind global events
3681 OO
.ui
.WindowManager
.prototype.toggleGlobalEvents = function ( on
) {
3682 var scrollWidth
, bodyMargin
,
3683 $body
= $( this.getElementDocument().body
),
3684 // We could have multiple window managers open so only modify
3685 // the body css at the bottom of the stack
3686 stackDepth
= $body
.data( 'windowManagerGlobalEvents' ) || 0 ;
3688 on
= on
=== undefined ? !!this.globalEvents
: !!on
;
3691 if ( !this.globalEvents
) {
3692 $( this.getElementWindow() ).on( {
3693 // Start listening for top-level window dimension changes
3694 'orientationchange resize': this.onWindowResizeHandler
3696 if ( stackDepth
=== 0 ) {
3697 scrollWidth
= window
.innerWidth
- document
.documentElement
.clientWidth
;
3698 bodyMargin
= parseFloat( $body
.css( 'margin-right' ) ) || 0;
3701 'margin-right': bodyMargin
+ scrollWidth
3705 this.globalEvents
= true;
3707 } else if ( this.globalEvents
) {
3708 $( this.getElementWindow() ).off( {
3709 // Stop listening for top-level window dimension changes
3710 'orientationchange resize': this.onWindowResizeHandler
3713 if ( stackDepth
=== 0 ) {
3719 this.globalEvents
= false;
3721 $body
.data( 'windowManagerGlobalEvents', stackDepth
);
3727 * Toggle screen reader visibility of content other than the window manager.
3730 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3733 OO
.ui
.WindowManager
.prototype.toggleAriaIsolation = function ( isolate
) {
3734 isolate
= isolate
=== undefined ? !this.$ariaHidden
: !!isolate
;
3737 if ( !this.$ariaHidden
) {
3738 // Hide everything other than the window manager from screen readers
3739 this.$ariaHidden
= $( 'body' )
3741 .not( this.$element
.parentsUntil( 'body' ).last() )
3742 .attr( 'aria-hidden', '' );
3744 } else if ( this.$ariaHidden
) {
3745 // Restore screen reader visibility
3746 this.$ariaHidden
.removeAttr( 'aria-hidden' );
3747 this.$ariaHidden
= null;
3754 * Destroy the window manager.
3756 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3757 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3760 OO
.ui
.WindowManager
.prototype.destroy = function () {
3761 this.toggleGlobalEvents( false );
3762 this.toggleAriaIsolation( false );
3763 this.clearWindows();
3764 this.$element
.remove();
3768 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3769 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3770 * appearance and functionality of the error interface.
3772 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3773 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3774 * that initiated the failed process will be disabled.
3776 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3779 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3781 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3786 * @param {string|jQuery} message Description of error
3787 * @param {Object} [config] Configuration options
3788 * @cfg {boolean} [recoverable=true] Error is recoverable.
3789 * By default, errors are recoverable, and users can try the process again.
3790 * @cfg {boolean} [warning=false] Error is a warning.
3791 * If the error is a warning, the error interface will include a
3792 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3793 * is not triggered a second time if the user chooses to continue.
3795 OO
.ui
.Error
= function OoUiError( message
, config
) {
3796 // Allow passing positional parameters inside the config object
3797 if ( OO
.isPlainObject( message
) && config
=== undefined ) {
3799 message
= config
.message
;
3802 // Configuration initialization
3803 config
= config
|| {};
3806 this.message
= message
instanceof jQuery
? message
: String( message
);
3807 this.recoverable
= config
.recoverable
=== undefined || !!config
.recoverable
;
3808 this.warning
= !!config
.warning
;
3813 OO
.initClass( OO
.ui
.Error
);
3818 * Check if the error is recoverable.
3820 * If the error is recoverable, users are able to try the process again.
3822 * @return {boolean} Error is recoverable
3824 OO
.ui
.Error
.prototype.isRecoverable = function () {
3825 return this.recoverable
;
3829 * Check if the error is a warning.
3831 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3833 * @return {boolean} Error is warning
3835 OO
.ui
.Error
.prototype.isWarning = function () {
3836 return this.warning
;
3840 * Get error message as DOM nodes.
3842 * @return {jQuery} Error message in DOM nodes
3844 OO
.ui
.Error
.prototype.getMessage = function () {
3845 return this.message
instanceof jQuery
?
3846 this.message
.clone() :
3847 $( '<div>' ).text( this.message
).contents();
3851 * Get the error message text.
3853 * @return {string} Error message
3855 OO
.ui
.Error
.prototype.getMessageText = function () {
3856 return this.message
instanceof jQuery
? this.message
.text() : this.message
;
3860 * Wraps an HTML snippet for use with configuration values which default
3861 * to strings. This bypasses the default html-escaping done to string
3867 * @param {string} [content] HTML content
3869 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
3871 this.content
= content
;
3876 OO
.initClass( OO
.ui
.HtmlSnippet
);
3883 * @return {string} Unchanged HTML snippet.
3885 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
3886 return this.content
;
3890 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3893 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3894 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3895 * or stop if the promise is rejected.
3896 * - **function**: the process will execute the function. The process will stop if the function returns
3897 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3898 * will wait for that number of milliseconds before proceeding.
3900 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3901 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3902 * its remaining steps will not be performed.
3907 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3908 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3909 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3910 * a number or promise.
3911 * @return {Object} Step object, with `callback` and `context` properties
3913 OO
.ui
.Process = function ( step
, context
) {
3918 if ( step
!== undefined ) {
3919 this.next( step
, context
);
3925 OO
.initClass( OO
.ui
.Process
);
3930 * Start the process.
3932 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
3933 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
3934 * and any remaining steps are not performed.
3936 OO
.ui
.Process
.prototype.execute = function () {
3937 var i
, len
, promise
;
3940 * Continue execution.
3943 * @param {Array} step A function and the context it should be called in
3944 * @return {Function} Function that continues the process
3946 function proceed( step
) {
3947 return function () {
3948 // Execute step in the correct context
3950 result
= step
.callback
.call( step
.context
);
3952 if ( result
=== false ) {
3953 // Use rejected promise for boolean false results
3954 return $.Deferred().reject( [] ).promise();
3956 if ( typeof result
=== 'number' ) {
3958 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3960 // Use a delayed promise for numbers, expecting them to be in milliseconds
3961 deferred
= $.Deferred();
3962 setTimeout( deferred
.resolve
, result
);
3963 return deferred
.promise();
3965 if ( result
instanceof OO
.ui
.Error
) {
3966 // Use rejected promise for error
3967 return $.Deferred().reject( [ result
] ).promise();
3969 if ( Array
.isArray( result
) && result
.length
&& result
[ 0 ] instanceof OO
.ui
.Error
) {
3970 // Use rejected promise for list of errors
3971 return $.Deferred().reject( result
).promise();
3973 // Duck-type the object to see if it can produce a promise
3974 if ( result
&& $.isFunction( result
.promise
) ) {
3975 // Use a promise generated from the result
3976 return result
.promise();
3978 // Use resolved promise for other results
3979 return $.Deferred().resolve().promise();
3983 if ( this.steps
.length
) {
3984 // Generate a chain reaction of promises
3985 promise
= proceed( this.steps
[ 0 ] )();
3986 for ( i
= 1, len
= this.steps
.length
; i
< len
; i
++ ) {
3987 promise
= promise
.then( proceed( this.steps
[ i
] ) );
3990 promise
= $.Deferred().resolve().promise();
3997 * Create a process step.
4000 * @param {number|jQuery.Promise|Function} step
4002 * - Number of milliseconds to wait before proceeding
4003 * - Promise that must be resolved before proceeding
4004 * - Function to execute
4005 * - If the function returns a boolean false the process will stop
4006 * - If the function returns a promise, the process will continue to the next
4007 * step when the promise is resolved or stop if the promise is rejected
4008 * - If the function returns a number, the process will wait for that number of
4009 * milliseconds before proceeding
4010 * @param {Object} [context=null] Execution context of the function. The context is
4011 * ignored if the step is a number or promise.
4012 * @return {Object} Step object, with `callback` and `context` properties
4014 OO
.ui
.Process
.prototype.createStep = function ( step
, context
) {
4015 if ( typeof step
=== 'number' || $.isFunction( step
.promise
) ) {
4017 callback: function () {
4023 if ( $.isFunction( step
) ) {
4029 throw new Error( 'Cannot create process step: number, promise or function expected' );
4033 * Add step to the beginning of the process.
4035 * @inheritdoc #createStep
4036 * @return {OO.ui.Process} this
4039 OO
.ui
.Process
.prototype.first = function ( step
, context
) {
4040 this.steps
.unshift( this.createStep( step
, context
) );
4045 * Add step to the end of the process.
4047 * @inheritdoc #createStep
4048 * @return {OO.ui.Process} this
4051 OO
.ui
.Process
.prototype.next = function ( step
, context
) {
4052 this.steps
.push( this.createStep( step
, context
) );
4057 * A ToolFactory creates tools on demand. All tools ({@link OO.ui.Tool Tools}, {@link OO.ui.PopupTool PopupTools},
4058 * and {@link OO.ui.ToolGroupTool ToolGroupTools}) must be registered with a tool factory. Tools are
4059 * registered by their symbolic name. See {@link OO.ui.Toolbar toolbars} for an example.
4061 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4063 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4066 * @extends OO.Factory
4069 OO
.ui
.ToolFactory
= function OoUiToolFactory() {
4070 // Parent constructor
4071 OO
.ui
.ToolFactory
.parent
.call( this );
4076 OO
.inheritClass( OO
.ui
.ToolFactory
, OO
.Factory
);
4081 * Get tools from the factory
4083 * @param {Array} include Included tools
4084 * @param {Array} exclude Excluded tools
4085 * @param {Array} promote Promoted tools
4086 * @param {Array} demote Demoted tools
4087 * @return {string[]} List of tools
4089 OO
.ui
.ToolFactory
.prototype.getTools = function ( include
, exclude
, promote
, demote
) {
4090 var i
, len
, included
, promoted
, demoted
,
4094 // Collect included and not excluded tools
4095 included
= OO
.simpleArrayDifference( this.extract( include
), this.extract( exclude
) );
4098 promoted
= this.extract( promote
, used
);
4099 demoted
= this.extract( demote
, used
);
4102 for ( i
= 0, len
= included
.length
; i
< len
; i
++ ) {
4103 if ( !used
[ included
[ i
] ] ) {
4104 auto
.push( included
[ i
] );
4108 return promoted
.concat( auto
).concat( demoted
);
4112 * Get a flat list of names from a list of names or groups.
4114 * Tools can be specified in the following ways:
4116 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
4117 * - All tools in a group: `{ group: 'group-name' }`
4118 * - All tools: `'*'`
4121 * @param {Array|string} collection List of tools
4122 * @param {Object} [used] Object with names that should be skipped as properties; extracted
4123 * names will be added as properties
4124 * @return {string[]} List of extracted names
4126 OO
.ui
.ToolFactory
.prototype.extract = function ( collection
, used
) {
4127 var i
, len
, item
, name
, tool
,
4130 if ( collection
=== '*' ) {
4131 for ( name
in this.registry
) {
4132 tool
= this.registry
[ name
];
4134 // Only add tools by group name when auto-add is enabled
4135 tool
.static.autoAddToCatchall
&&
4136 // Exclude already used tools
4137 ( !used
|| !used
[ name
] )
4141 used
[ name
] = true;
4145 } else if ( Array
.isArray( collection
) ) {
4146 for ( i
= 0, len
= collection
.length
; i
< len
; i
++ ) {
4147 item
= collection
[ i
];
4148 // Allow plain strings as shorthand for named tools
4149 if ( typeof item
=== 'string' ) {
4150 item
= { name
: item
};
4152 if ( OO
.isPlainObject( item
) ) {
4154 for ( name
in this.registry
) {
4155 tool
= this.registry
[ name
];
4157 // Include tools with matching group
4158 tool
.static.group
=== item
.group
&&
4159 // Only add tools by group name when auto-add is enabled
4160 tool
.static.autoAddToGroup
&&
4161 // Exclude already used tools
4162 ( !used
|| !used
[ name
] )
4166 used
[ name
] = true;
4170 // Include tools with matching name and exclude already used tools
4171 } else if ( item
.name
&& ( !used
|| !used
[ item
.name
] ) ) {
4172 names
.push( item
.name
);
4174 used
[ item
.name
] = true;
4184 * ToolGroupFactories create {@link OO.ui.ToolGroup toolgroups} on demand. The toolgroup classes must
4185 * specify a symbolic name and be registered with the factory. The following classes are registered by
4188 * - {@link OO.ui.BarToolGroup BarToolGroups} (‘bar’)
4189 * - {@link OO.ui.MenuToolGroup MenuToolGroups} (‘menu’)
4190 * - {@link OO.ui.ListToolGroup ListToolGroups} (‘list’)
4192 * See {@link OO.ui.Toolbar toolbars} for an example.
4194 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4196 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4198 * @extends OO.Factory
4201 OO
.ui
.ToolGroupFactory
= function OoUiToolGroupFactory() {
4202 var i
, l
, defaultClasses
;
4203 // Parent constructor
4204 OO
.Factory
.call( this );
4206 defaultClasses
= this.constructor.static.getDefaultClasses();
4208 // Register default toolgroups
4209 for ( i
= 0, l
= defaultClasses
.length
; i
< l
; i
++ ) {
4210 this.register( defaultClasses
[ i
] );
4216 OO
.inheritClass( OO
.ui
.ToolGroupFactory
, OO
.Factory
);
4218 /* Static Methods */
4221 * Get a default set of classes to be registered on construction.
4223 * @return {Function[]} Default classes
4225 OO
.ui
.ToolGroupFactory
.static.getDefaultClasses = function () {
4228 OO
.ui
.ListToolGroup
,
4240 * @param {Object} [config] Configuration options
4242 OO
.ui
.Theme
= function OoUiTheme( config
) {
4243 // Configuration initialization
4244 config
= config
|| {};
4249 OO
.initClass( OO
.ui
.Theme
);
4254 * Get a list of classes to be applied to a widget.
4256 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
4257 * otherwise state transitions will not work properly.
4259 * @param {OO.ui.Element} element Element for which to get classes
4260 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4262 OO
.ui
.Theme
.prototype.getElementClasses = function () {
4263 return { on
: [], off
: [] };
4267 * Update CSS classes provided by the theme.
4269 * For elements with theme logic hooks, this should be called any time there's a state change.
4271 * @param {OO.ui.Element} element Element for which to update classes
4272 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4274 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
4275 var $elements
= $( [] ),
4276 classes
= this.getElementClasses( element
);
4278 if ( element
.$icon
) {
4279 $elements
= $elements
.add( element
.$icon
);
4281 if ( element
.$indicator
) {
4282 $elements
= $elements
.add( element
.$indicator
);
4286 .removeClass( classes
.off
.join( ' ' ) )
4287 .addClass( classes
.on
.join( ' ' ) );
4291 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
4292 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
4293 * order in which users will navigate through the focusable elements via the "tab" key.
4296 * // TabIndexedElement is mixed into the ButtonWidget class
4297 * // to provide a tabIndex property.
4298 * var button1 = new OO.ui.ButtonWidget( {
4302 * var button2 = new OO.ui.ButtonWidget( {
4306 * var button3 = new OO.ui.ButtonWidget( {
4310 * var button4 = new OO.ui.ButtonWidget( {
4314 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
4320 * @param {Object} [config] Configuration options
4321 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
4322 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
4323 * functionality will be applied to it instead.
4324 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
4325 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
4326 * to remove the element from the tab-navigation flow.
4328 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
4329 // Configuration initialization
4330 config
= $.extend( { tabIndex
: 0 }, config
);
4333 this.$tabIndexed
= null;
4334 this.tabIndex
= null;
4337 this.connect( this, { disable
: 'onTabIndexedElementDisable' } );
4340 this.setTabIndex( config
.tabIndex
);
4341 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
4346 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
4351 * Set the element that should use the tabindex functionality.
4353 * This method is used to retarget a tabindex mixin so that its functionality applies
4354 * to the specified element. If an element is currently using the functionality, the mixin’s
4355 * effect on that element is removed before the new element is set up.
4357 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
4360 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
4361 var tabIndex
= this.tabIndex
;
4362 // Remove attributes from old $tabIndexed
4363 this.setTabIndex( null );
4364 // Force update of new $tabIndexed
4365 this.$tabIndexed
= $tabIndexed
;
4366 this.tabIndex
= tabIndex
;
4367 return this.updateTabIndex();
4371 * Set the value of the tabindex.
4373 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
4376 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
4377 tabIndex
= typeof tabIndex
=== 'number' ? tabIndex
: null;
4379 if ( this.tabIndex
!== tabIndex
) {
4380 this.tabIndex
= tabIndex
;
4381 this.updateTabIndex();
4388 * Update the `tabindex` attribute, in case of changes to tab index or
4394 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
4395 if ( this.$tabIndexed
) {
4396 if ( this.tabIndex
!== null ) {
4397 // Do not index over disabled elements
4398 this.$tabIndexed
.attr( {
4399 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
4400 // Support: ChromeVox and NVDA
4401 // These do not seem to inherit aria-disabled from parent elements
4402 'aria-disabled': this.isDisabled().toString()
4405 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
4412 * Handle disable events.
4415 * @param {boolean} disabled Element is disabled
4417 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
4418 this.updateTabIndex();
4422 * Get the value of the tabindex.
4424 * @return {number|null} Tabindex value
4426 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
4427 return this.tabIndex
;
4431 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
4432 * interface element that can be configured with access keys for accessibility.
4433 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
4435 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
4440 * @param {Object} [config] Configuration options
4441 * @cfg {jQuery} [$button] The button element created by the class.
4442 * If this configuration is omitted, the button element will use a generated `<a>`.
4443 * @cfg {boolean} [framed=true] Render the button with a frame
4445 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
4446 // Configuration initialization
4447 config
= config
|| {};
4450 this.$button
= null;
4452 this.active
= false;
4453 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
4454 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
4455 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
4456 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
4457 this.onClickHandler
= this.onClick
.bind( this );
4458 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
4461 this.$element
.addClass( 'oo-ui-buttonElement' );
4462 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
4463 this.setButtonElement( config
.$button
|| $( '<a>' ) );
4468 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
4470 /* Static Properties */
4473 * Cancel mouse down events.
4475 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4476 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4477 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4482 * @property {boolean}
4484 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
4489 * A 'click' event is emitted when the button element is clicked.
4497 * Set the button element.
4499 * This method is used to retarget a button mixin so that its functionality applies to
4500 * the specified button element instead of the one created by the class. If a button element
4501 * is already set, the method will remove the mixin’s effect on that element.
4503 * @param {jQuery} $button Element to use as button
4505 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
4506 if ( this.$button
) {
4508 .removeClass( 'oo-ui-buttonElement-button' )
4509 .removeAttr( 'role accesskey' )
4511 mousedown
: this.onMouseDownHandler
,
4512 keydown
: this.onKeyDownHandler
,
4513 click
: this.onClickHandler
,
4514 keypress
: this.onKeyPressHandler
4518 this.$button
= $button
4519 .addClass( 'oo-ui-buttonElement-button' )
4520 .attr( { role
: 'button' } )
4522 mousedown
: this.onMouseDownHandler
,
4523 keydown
: this.onKeyDownHandler
,
4524 click
: this.onClickHandler
,
4525 keypress
: this.onKeyPressHandler
4530 * Handles mouse down events.
4533 * @param {jQuery.Event} e Mouse down event
4535 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
4536 if ( this.isDisabled() || e
.which
!== 1 ) {
4539 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4540 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4541 // reliably remove the pressed class
4542 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler
);
4543 // Prevent change of focus unless specifically configured otherwise
4544 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
4550 * Handles mouse up events.
4553 * @param {jQuery.Event} e Mouse up event
4555 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp = function ( e
) {
4556 if ( this.isDisabled() || e
.which
!== 1 ) {
4559 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4560 // Stop listening for mouseup, since we only needed this once
4561 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler
);
4565 * Handles mouse click events.
4568 * @param {jQuery.Event} e Mouse click event
4571 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
4572 if ( !this.isDisabled() && e
.which
=== 1 ) {
4573 if ( this.emit( 'click' ) ) {
4580 * Handles key down events.
4583 * @param {jQuery.Event} e Key down event
4585 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
4586 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4589 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4590 // Run the keyup handler no matter where the key is when the button is let go, so we can
4591 // reliably remove the pressed class
4592 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler
);
4596 * Handles key up events.
4599 * @param {jQuery.Event} e Key up event
4601 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyUp = function ( e
) {
4602 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4605 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4606 // Stop listening for keyup, since we only needed this once
4607 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler
);
4611 * Handles key press events.
4614 * @param {jQuery.Event} e Key press event
4617 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
4618 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
4619 if ( this.emit( 'click' ) ) {
4626 * Check if button has a frame.
4628 * @return {boolean} Button is framed
4630 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
4635 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4637 * @param {boolean} [framed] Make button framed, omit to toggle
4640 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
4641 framed
= framed
=== undefined ? !this.framed
: !!framed
;
4642 if ( framed
!== this.framed
) {
4643 this.framed
= framed
;
4645 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
4646 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
4647 this.updateThemeClasses();
4654 * Set the button's active state.
4656 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4657 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4658 * for other button types.
4660 * @param {boolean} value Make button active
4663 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
4664 this.active
= !!value
;
4665 this.$element
.toggleClass( 'oo-ui-buttonElement-active', this.active
);
4670 * Check if the button is active
4672 * @return {boolean} The button is active
4674 OO
.ui
.mixin
.ButtonElement
.prototype.isActive = function () {
4679 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4680 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4681 * items from the group is done through the interface the class provides.
4682 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4684 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4690 * @param {Object} [config] Configuration options
4691 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4692 * is omitted, the group element will use a generated `<div>`.
4694 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
4695 // Configuration initialization
4696 config
= config
|| {};
4701 this.aggregateItemEvents
= {};
4704 this.setGroupElement( config
.$group
|| $( '<div>' ) );
4710 * Set the group element.
4712 * If an element is already set, items will be moved to the new element.
4714 * @param {jQuery} $group Element to use as group
4716 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
4719 this.$group
= $group
;
4720 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4721 this.$group
.append( this.items
[ i
].$element
);
4726 * Check if a group contains no items.
4728 * @return {boolean} Group is empty
4730 OO
.ui
.mixin
.GroupElement
.prototype.isEmpty = function () {
4731 return !this.items
.length
;
4735 * Get all items in the group.
4737 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4738 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4741 * @return {OO.ui.Element[]} An array of items.
4743 OO
.ui
.mixin
.GroupElement
.prototype.getItems = function () {
4744 return this.items
.slice( 0 );
4748 * Get an item by its data.
4750 * Only the first item with matching data will be returned. To return all matching items,
4751 * use the #getItemsFromData method.
4753 * @param {Object} data Item data to search for
4754 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4756 OO
.ui
.mixin
.GroupElement
.prototype.getItemFromData = function ( data
) {
4758 hash
= OO
.getHash( data
);
4760 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4761 item
= this.items
[ i
];
4762 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4771 * Get items by their data.
4773 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4775 * @param {Object} data Item data to search for
4776 * @return {OO.ui.Element[]} Items with equivalent data
4778 OO
.ui
.mixin
.GroupElement
.prototype.getItemsFromData = function ( data
) {
4780 hash
= OO
.getHash( data
),
4783 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4784 item
= this.items
[ i
];
4785 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4794 * Aggregate the events emitted by the group.
4796 * When events are aggregated, the group will listen to all contained items for the event,
4797 * and then emit the event under a new name. The new event will contain an additional leading
4798 * parameter containing the item that emitted the original event. Other arguments emitted from
4799 * the original event are passed through.
4801 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4802 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4803 * A `null` value will remove aggregated events.
4805 * @throws {Error} An error is thrown if aggregation already exists.
4807 OO
.ui
.mixin
.GroupElement
.prototype.aggregate = function ( events
) {
4808 var i
, len
, item
, add
, remove
, itemEvent
, groupEvent
;
4810 for ( itemEvent
in events
) {
4811 groupEvent
= events
[ itemEvent
];
4813 // Remove existing aggregated event
4814 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4815 // Don't allow duplicate aggregations
4817 throw new Error( 'Duplicate item event aggregation for ' + itemEvent
);
4819 // Remove event aggregation from existing items
4820 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4821 item
= this.items
[ i
];
4822 if ( item
.connect
&& item
.disconnect
) {
4824 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4825 item
.disconnect( this, remove
);
4828 // Prevent future items from aggregating event
4829 delete this.aggregateItemEvents
[ itemEvent
];
4832 // Add new aggregate event
4834 // Make future items aggregate event
4835 this.aggregateItemEvents
[ itemEvent
] = groupEvent
;
4836 // Add event aggregation to existing items
4837 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4838 item
= this.items
[ i
];
4839 if ( item
.connect
&& item
.disconnect
) {
4841 add
[ itemEvent
] = [ 'emit', groupEvent
, item
];
4842 item
.connect( this, add
);
4850 * Add items to the group.
4852 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4853 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4855 * @param {OO.ui.Element[]} items An array of items to add to the group
4856 * @param {number} [index] Index of the insertion point
4859 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
4860 var i
, len
, item
, event
, events
, currentIndex
,
4863 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4866 // Check if item exists then remove it first, effectively "moving" it
4867 currentIndex
= this.items
.indexOf( item
);
4868 if ( currentIndex
>= 0 ) {
4869 this.removeItems( [ item
] );
4870 // Adjust index to compensate for removal
4871 if ( currentIndex
< index
) {
4876 if ( item
.connect
&& item
.disconnect
&& !$.isEmptyObject( this.aggregateItemEvents
) ) {
4878 for ( event
in this.aggregateItemEvents
) {
4879 events
[ event
] = [ 'emit', this.aggregateItemEvents
[ event
], item
];
4881 item
.connect( this, events
);
4883 item
.setElementGroup( this );
4884 itemElements
.push( item
.$element
.get( 0 ) );
4887 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
4888 this.$group
.append( itemElements
);
4889 this.items
.push
.apply( this.items
, items
);
4890 } else if ( index
=== 0 ) {
4891 this.$group
.prepend( itemElements
);
4892 this.items
.unshift
.apply( this.items
, items
);
4894 this.items
[ index
].$element
.before( itemElements
);
4895 this.items
.splice
.apply( this.items
, [ index
, 0 ].concat( items
) );
4902 * Remove the specified items from a group.
4904 * Removed items are detached (not removed) from the DOM so that they may be reused.
4905 * To remove all items from a group, you may wish to use the #clearItems method instead.
4907 * @param {OO.ui.Element[]} items An array of items to remove
4910 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
4911 var i
, len
, item
, index
, remove
, itemEvent
;
4913 // Remove specific items
4914 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4916 index
= this.items
.indexOf( item
);
4917 if ( index
!== -1 ) {
4919 item
.connect
&& item
.disconnect
&&
4920 !$.isEmptyObject( this.aggregateItemEvents
)
4923 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4924 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4926 item
.disconnect( this, remove
);
4928 item
.setElementGroup( null );
4929 this.items
.splice( index
, 1 );
4930 item
.$element
.detach();
4938 * Clear all items from the group.
4940 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4941 * To remove only a subset of items from a group, use the #removeItems method.
4945 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
4946 var i
, len
, item
, remove
, itemEvent
;
4949 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4950 item
= this.items
[ i
];
4952 item
.connect
&& item
.disconnect
&&
4953 !$.isEmptyObject( this.aggregateItemEvents
)
4956 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4957 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4959 item
.disconnect( this, remove
);
4961 item
.setElementGroup( null );
4962 item
.$element
.detach();
4970 * DraggableElement is a mixin class used to create elements that can be clicked
4971 * and dragged by a mouse to a new position within a group. This class must be used
4972 * in conjunction with OO.ui.mixin.DraggableGroupElement, which provides a container for
4973 * the draggable elements.
4980 OO
.ui
.mixin
.DraggableElement
= function OoUiMixinDraggableElement() {
4984 // Initialize and events
4986 .attr( 'draggable', true )
4987 .addClass( 'oo-ui-draggableElement' )
4989 dragstart
: this.onDragStart
.bind( this ),
4990 dragover
: this.onDragOver
.bind( this ),
4991 dragend
: this.onDragEnd
.bind( this ),
4992 drop
: this.onDrop
.bind( this )
4996 OO
.initClass( OO
.ui
.mixin
.DraggableElement
);
5003 * A dragstart event is emitted when the user clicks and begins dragging an item.
5004 * @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse.
5009 * A dragend event is emitted when the user drags an item and releases the mouse,
5010 * thus terminating the drag operation.
5015 * A drop event is emitted when the user drags an item and then releases the mouse button
5016 * over a valid target.
5019 /* Static Properties */
5022 * @inheritdoc OO.ui.mixin.ButtonElement
5024 OO
.ui
.mixin
.DraggableElement
.static.cancelButtonMouseDownEvents
= false;
5029 * Respond to dragstart event.
5032 * @param {jQuery.Event} event jQuery event
5035 OO
.ui
.mixin
.DraggableElement
.prototype.onDragStart = function ( e
) {
5036 var dataTransfer
= e
.originalEvent
.dataTransfer
;
5037 // Define drop effect
5038 dataTransfer
.dropEffect
= 'none';
5039 dataTransfer
.effectAllowed
= 'move';
5041 // We must set up a dataTransfer data property or Firefox seems to
5042 // ignore the fact the element is draggable.
5044 dataTransfer
.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
5046 // The above is only for Firefox. Move on if it fails.
5048 // Add dragging class
5049 this.$element
.addClass( 'oo-ui-draggableElement-dragging' );
5051 this.emit( 'dragstart', this );
5056 * Respond to dragend event.
5061 OO
.ui
.mixin
.DraggableElement
.prototype.onDragEnd = function () {
5062 this.$element
.removeClass( 'oo-ui-draggableElement-dragging' );
5063 this.emit( 'dragend' );
5067 * Handle drop event.
5070 * @param {jQuery.Event} event jQuery event
5073 OO
.ui
.mixin
.DraggableElement
.prototype.onDrop = function ( e
) {
5075 this.emit( 'drop', e
);
5079 * In order for drag/drop to work, the dragover event must
5080 * return false and stop propogation.
5084 OO
.ui
.mixin
.DraggableElement
.prototype.onDragOver = function ( e
) {
5090 * Store it in the DOM so we can access from the widget drag event
5093 * @param {number} Item index
5095 OO
.ui
.mixin
.DraggableElement
.prototype.setIndex = function ( index
) {
5096 if ( this.index
!== index
) {
5098 this.$element
.data( 'index', index
);
5106 * @return {number} Item index
5108 OO
.ui
.mixin
.DraggableElement
.prototype.getIndex = function () {
5113 * DraggableGroupElement is a mixin class used to create a group element to
5114 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
5115 * The class is used with OO.ui.mixin.DraggableElement.
5119 * @mixins OO.ui.mixin.GroupElement
5122 * @param {Object} [config] Configuration options
5123 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
5124 * should match the layout of the items. Items displayed in a single row
5125 * or in several rows should use horizontal orientation. The vertical orientation should only be
5126 * used when the items are displayed in a single column. Defaults to 'vertical'
5128 OO
.ui
.mixin
.DraggableGroupElement
= function OoUiMixinDraggableGroupElement( config
) {
5129 // Configuration initialization
5130 config
= config
|| {};
5132 // Parent constructor
5133 OO
.ui
.mixin
.GroupElement
.call( this, config
);
5136 this.orientation
= config
.orientation
|| 'vertical';
5137 this.dragItem
= null;
5138 this.itemDragOver
= null;
5140 this.sideInsertion
= '';
5144 dragstart
: 'itemDragStart',
5145 dragend
: 'itemDragEnd',
5148 this.connect( this, {
5149 itemDragStart
: 'onItemDragStart',
5150 itemDrop
: 'onItemDrop',
5151 itemDragEnd
: 'onItemDragEnd'
5154 dragover
: this.onDragOver
.bind( this ),
5155 dragleave
: this.onDragLeave
.bind( this )
5159 if ( Array
.isArray( config
.items
) ) {
5160 this.addItems( config
.items
);
5162 this.$placeholder
= $( '<div>' )
5163 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
5165 .addClass( 'oo-ui-draggableGroupElement' )
5166 .append( this.$status
)
5167 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation
=== 'horizontal' )
5168 .prepend( this.$placeholder
);
5172 OO
.mixinClass( OO
.ui
.mixin
.DraggableGroupElement
, OO
.ui
.mixin
.GroupElement
);
5177 * A 'reorder' event is emitted when the order of items in the group changes.
5180 * @param {OO.ui.mixin.DraggableElement} item Reordered item
5181 * @param {number} [newIndex] New index for the item
5187 * Respond to item drag start event
5190 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5192 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDragStart = function ( item
) {
5195 // Map the index of each object
5196 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5197 this.items
[ i
].setIndex( i
);
5200 if ( this.orientation
=== 'horizontal' ) {
5201 // Set the height of the indicator
5202 this.$placeholder
.css( {
5203 height
: item
.$element
.outerHeight(),
5207 // Set the width of the indicator
5208 this.$placeholder
.css( {
5210 width
: item
.$element
.outerWidth()
5213 this.setDragItem( item
);
5217 * Respond to item drag end event
5221 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDragEnd = function () {
5222 this.unsetDragItem();
5227 * Handle drop event and switch the order of the items accordingly
5230 * @param {OO.ui.mixin.DraggableElement} item Dropped item
5233 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDrop = function ( item
) {
5234 var toIndex
= item
.getIndex();
5235 // Check if the dropped item is from the current group
5236 // TODO: Figure out a way to configure a list of legally droppable
5237 // elements even if they are not yet in the list
5238 if ( this.getDragItem() ) {
5239 // If the insertion point is 'after', the insertion index
5240 // is shifted to the right (or to the left in RTL, hence 'after')
5241 if ( this.sideInsertion
=== 'after' ) {
5244 // Emit change event
5245 this.emit( 'reorder', this.getDragItem(), toIndex
);
5247 this.unsetDragItem();
5248 // Return false to prevent propogation
5253 * Handle dragleave event.
5257 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onDragLeave = function () {
5258 // This means the item was dragged outside the widget
5261 .addClass( 'oo-ui-element-hidden' );
5265 * Respond to dragover event
5268 * @param {jQuery.Event} event Event details
5270 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onDragOver = function ( e
) {
5271 var dragOverObj
, $optionWidget
, itemOffset
, itemMidpoint
, itemBoundingRect
,
5272 itemSize
, cssOutput
, dragPosition
, itemIndex
, itemPosition
,
5273 clientX
= e
.originalEvent
.clientX
,
5274 clientY
= e
.originalEvent
.clientY
;
5276 // Get the OptionWidget item we are dragging over
5277 dragOverObj
= this.getElementDocument().elementFromPoint( clientX
, clientY
);
5278 $optionWidget
= $( dragOverObj
).closest( '.oo-ui-draggableElement' );
5279 if ( $optionWidget
[ 0 ] ) {
5280 itemOffset
= $optionWidget
.offset();
5281 itemBoundingRect
= $optionWidget
[ 0 ].getBoundingClientRect();
5282 itemPosition
= $optionWidget
.position();
5283 itemIndex
= $optionWidget
.data( 'index' );
5288 this.isDragging() &&
5289 itemIndex
!== this.getDragItem().getIndex()
5291 if ( this.orientation
=== 'horizontal' ) {
5292 // Calculate where the mouse is relative to the item width
5293 itemSize
= itemBoundingRect
.width
;
5294 itemMidpoint
= itemBoundingRect
.left
+ itemSize
/ 2;
5295 dragPosition
= clientX
;
5296 // Which side of the item we hover over will dictate
5297 // where the placeholder will appear, on the left or
5300 left
: dragPosition
< itemMidpoint
? itemPosition
.left
: itemPosition
.left
+ itemSize
,
5301 top
: itemPosition
.top
5304 // Calculate where the mouse is relative to the item height
5305 itemSize
= itemBoundingRect
.height
;
5306 itemMidpoint
= itemBoundingRect
.top
+ itemSize
/ 2;
5307 dragPosition
= clientY
;
5308 // Which side of the item we hover over will dictate
5309 // where the placeholder will appear, on the top or
5312 top
: dragPosition
< itemMidpoint
? itemPosition
.top
: itemPosition
.top
+ itemSize
,
5313 left
: itemPosition
.left
5316 // Store whether we are before or after an item to rearrange
5317 // For horizontal layout, we need to account for RTL, as this is flipped
5318 if ( this.orientation
=== 'horizontal' && this.$element
.css( 'direction' ) === 'rtl' ) {
5319 this.sideInsertion
= dragPosition
< itemMidpoint
? 'after' : 'before';
5321 this.sideInsertion
= dragPosition
< itemMidpoint
? 'before' : 'after';
5323 // Add drop indicator between objects
5326 .removeClass( 'oo-ui-element-hidden' );
5328 // This means the item was dragged outside the widget
5331 .addClass( 'oo-ui-element-hidden' );
5338 * Set a dragged item
5340 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5342 OO
.ui
.mixin
.DraggableGroupElement
.prototype.setDragItem = function ( item
) {
5343 this.dragItem
= item
;
5347 * Unset the current dragged item
5349 OO
.ui
.mixin
.DraggableGroupElement
.prototype.unsetDragItem = function () {
5350 this.dragItem
= null;
5351 this.itemDragOver
= null;
5352 this.$placeholder
.addClass( 'oo-ui-element-hidden' );
5353 this.sideInsertion
= '';
5357 * Get the item that is currently being dragged.
5359 * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
5361 OO
.ui
.mixin
.DraggableGroupElement
.prototype.getDragItem = function () {
5362 return this.dragItem
;
5366 * Check if an item in the group is currently being dragged.
5368 * @return {Boolean} Item is being dragged
5370 OO
.ui
.mixin
.DraggableGroupElement
.prototype.isDragging = function () {
5371 return this.getDragItem() !== null;
5375 * IconElement is often mixed into other classes to generate an icon.
5376 * Icons are graphics, about the size of normal text. They are used to aid the user
5377 * in locating a control or to convey information in a space-efficient way. See the
5378 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
5379 * included in the library.
5381 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5387 * @param {Object} [config] Configuration options
5388 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
5389 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
5390 * the icon element be set to an existing icon instead of the one generated by this class, set a
5391 * value using a jQuery selection. For example:
5393 * // Use a <div> tag instead of a <span>
5395 * // Use an existing icon element instead of the one generated by the class
5396 * $icon: this.$element
5397 * // Use an icon element from a child widget
5398 * $icon: this.childwidget.$element
5399 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
5400 * symbolic names. A map is used for i18n purposes and contains a `default` icon
5401 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
5402 * by the user's language.
5404 * Example of an i18n map:
5406 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5407 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
5408 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5409 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
5410 * text. The icon title is displayed when users move the mouse over the icon.
5412 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
5413 // Configuration initialization
5414 config
= config
|| {};
5419 this.iconTitle
= null;
5422 this.setIcon( config
.icon
|| this.constructor.static.icon
);
5423 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
5424 this.setIconElement( config
.$icon
|| $( '<span>' ) );
5429 OO
.initClass( OO
.ui
.mixin
.IconElement
);
5431 /* Static Properties */
5434 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
5435 * for i18n purposes and contains a `default` icon name and additional names keyed by
5436 * language code. The `default` name is used when no icon is keyed by the user's language.
5438 * Example of an i18n map:
5440 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5442 * Note: the static property will be overridden if the #icon configuration is used.
5446 * @property {Object|string}
5448 OO
.ui
.mixin
.IconElement
.static.icon
= null;
5451 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5452 * function that returns title text, or `null` for no title.
5454 * The static property will be overridden if the #iconTitle configuration is used.
5458 * @property {string|Function|null}
5460 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
5465 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5466 * applies to the specified icon element instead of the one created by the class. If an icon
5467 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5468 * and mixin methods will no longer affect the element.
5470 * @param {jQuery} $icon Element to use as icon
5472 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
5475 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
5476 .removeAttr( 'title' );
5480 .addClass( 'oo-ui-iconElement-icon' )
5481 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
5482 if ( this.iconTitle
!== null ) {
5483 this.$icon
.attr( 'title', this.iconTitle
);
5486 this.updateThemeClasses();
5490 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5491 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5494 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5495 * by language code, or `null` to remove the icon.
5498 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
5499 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
5500 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
5502 if ( this.icon
!== icon
) {
5504 if ( this.icon
!== null ) {
5505 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
5507 if ( icon
!== null ) {
5508 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
5514 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
5515 this.updateThemeClasses();
5521 * Set the icon title. Use `null` to remove the title.
5523 * @param {string|Function|null} iconTitle A text string used as the icon title,
5524 * a function that returns title text, or `null` for no title.
5527 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
5528 iconTitle
= typeof iconTitle
=== 'function' ||
5529 ( typeof iconTitle
=== 'string' && iconTitle
.length
) ?
5530 OO
.ui
.resolveMsg( iconTitle
) : null;
5532 if ( this.iconTitle
!== iconTitle
) {
5533 this.iconTitle
= iconTitle
;
5535 if ( this.iconTitle
!== null ) {
5536 this.$icon
.attr( 'title', iconTitle
);
5538 this.$icon
.removeAttr( 'title' );
5547 * Get the symbolic name of the icon.
5549 * @return {string} Icon name
5551 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
5556 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5558 * @return {string} Icon title text
5560 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
5561 return this.iconTitle
;
5565 * IndicatorElement is often mixed into other classes to generate an indicator.
5566 * Indicators are small graphics that are generally used in two ways:
5568 * - To draw attention to the status of an item. For example, an indicator might be
5569 * used to show that an item in a list has errors that need to be resolved.
5570 * - To clarify the function of a control that acts in an exceptional way (a button
5571 * that opens a menu instead of performing an action directly, for example).
5573 * For a list of indicators included in the library, please see the
5574 * [OOjs UI documentation on MediaWiki] [1].
5576 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5582 * @param {Object} [config] Configuration options
5583 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5584 * configuration is omitted, the indicator element will use a generated `<span>`.
5585 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5586 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5588 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5589 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5590 * or a function that returns title text. The indicator title is displayed when users move
5591 * the mouse over the indicator.
5593 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
5594 // Configuration initialization
5595 config
= config
|| {};
5598 this.$indicator
= null;
5599 this.indicator
= null;
5600 this.indicatorTitle
= null;
5603 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
5604 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
5605 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
5610 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
5612 /* Static Properties */
5615 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5616 * The static property will be overridden if the #indicator configuration is used.
5620 * @property {string|null}
5622 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
5625 * A text string used as the indicator title, a function that returns title text, or `null`
5626 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5630 * @property {string|Function|null}
5632 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
5637 * Set the indicator element.
5639 * If an element is already set, it will be cleaned up before setting up the new element.
5641 * @param {jQuery} $indicator Element to use as indicator
5643 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
5644 if ( this.$indicator
) {
5646 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
5647 .removeAttr( 'title' );
5650 this.$indicator
= $indicator
5651 .addClass( 'oo-ui-indicatorElement-indicator' )
5652 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
5653 if ( this.indicatorTitle
!== null ) {
5654 this.$indicator
.attr( 'title', this.indicatorTitle
);
5657 this.updateThemeClasses();
5661 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5663 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5666 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
5667 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
5669 if ( this.indicator
!== indicator
) {
5670 if ( this.$indicator
) {
5671 if ( this.indicator
!== null ) {
5672 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
5674 if ( indicator
!== null ) {
5675 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
5678 this.indicator
= indicator
;
5681 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
5682 this.updateThemeClasses();
5688 * Set the indicator title.
5690 * The title is displayed when a user moves the mouse over the indicator.
5692 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5693 * `null` for no indicator title
5696 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
5697 indicatorTitle
= typeof indicatorTitle
=== 'function' ||
5698 ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ?
5699 OO
.ui
.resolveMsg( indicatorTitle
) : null;
5701 if ( this.indicatorTitle
!== indicatorTitle
) {
5702 this.indicatorTitle
= indicatorTitle
;
5703 if ( this.$indicator
) {
5704 if ( this.indicatorTitle
!== null ) {
5705 this.$indicator
.attr( 'title', indicatorTitle
);
5707 this.$indicator
.removeAttr( 'title' );
5716 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5718 * @return {string} Symbolic name of indicator
5720 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
5721 return this.indicator
;
5725 * Get the indicator title.
5727 * The title is displayed when a user moves the mouse over the indicator.
5729 * @return {string} Indicator title text
5731 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
5732 return this.indicatorTitle
;
5736 * LabelElement is often mixed into other classes to generate a label, which
5737 * helps identify the function of an interface element.
5738 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5740 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5746 * @param {Object} [config] Configuration options
5747 * @cfg {jQuery} [$label] The label element created by the class. If this
5748 * configuration is omitted, the label element will use a generated `<span>`.
5749 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
5750 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
5751 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
5752 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5753 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5754 * The label will be truncated to fit if necessary.
5756 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
5757 // Configuration initialization
5758 config
= config
|| {};
5763 this.autoFitLabel
= config
.autoFitLabel
=== undefined || !!config
.autoFitLabel
;
5766 this.setLabel( config
.label
|| this.constructor.static.label
);
5767 this.setLabelElement( config
.$label
|| $( '<span>' ) );
5772 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
5777 * @event labelChange
5778 * @param {string} value
5781 /* Static Properties */
5784 * The label text. The label can be specified as a plaintext string, a function that will
5785 * produce a string in the future, or `null` for no label. The static value will
5786 * be overridden if a label is specified with the #label config option.
5790 * @property {string|Function|null}
5792 OO
.ui
.mixin
.LabelElement
.static.label
= null;
5797 * Set the label element.
5799 * If an element is already set, it will be cleaned up before setting up the new element.
5801 * @param {jQuery} $label Element to use as label
5803 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
5804 if ( this.$label
) {
5805 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
5808 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
5809 this.setLabelContent( this.label
);
5815 * An empty string will result in the label being hidden. A string containing only whitespace will
5816 * be converted to a single ` `.
5818 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5819 * text; or null for no label
5822 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
5823 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
5824 label
= ( ( typeof label
=== 'string' && label
.length
) || label
instanceof jQuery
|| label
instanceof OO
.ui
.HtmlSnippet
) ? label
: null;
5826 this.$element
.toggleClass( 'oo-ui-labelElement', !!label
);
5828 if ( this.label
!== label
) {
5829 if ( this.$label
) {
5830 this.setLabelContent( label
);
5833 this.emit( 'labelChange' );
5842 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5843 * text; or null for no label
5845 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
5854 OO
.ui
.mixin
.LabelElement
.prototype.fitLabel = function () {
5855 if ( this.$label
&& this.$label
.autoEllipsis
&& this.autoFitLabel
) {
5856 this.$label
.autoEllipsis( { hasSpan
: false, tooltip
: true } );
5863 * Set the content of the label.
5865 * Do not call this method until after the label element has been set by #setLabelElement.
5868 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5869 * text; or null for no label
5871 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
5872 if ( typeof label
=== 'string' ) {
5873 if ( label
.match( /^\s*$/ ) ) {
5874 // Convert whitespace only string to a single non-breaking space
5875 this.$label
.html( ' ' );
5877 this.$label
.text( label
);
5879 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
5880 this.$label
.html( label
.toString() );
5881 } else if ( label
instanceof jQuery
) {
5882 this.$label
.empty().append( label
);
5884 this.$label
.empty();
5889 * LookupElement is a mixin that creates a {@link OO.ui.FloatingMenuSelectWidget menu} of suggested values for
5890 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
5891 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
5892 * from the lookup menu, that value becomes the value of the input field.
5894 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
5895 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
5896 * re-enable lookups.
5898 * See the [OOjs UI demos][1] for an example.
5900 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
5906 * @param {Object} [config] Configuration options
5907 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
5908 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
5909 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
5910 * By default, the lookup menu is not generated and displayed until the user begins to type.
5911 * @cfg {boolean} [highlightFirst=true] Whether the first lookup result should be highlighted (so, that the user can
5912 * take it over into the input with simply pressing return) automatically or not.
5914 OO
.ui
.mixin
.LookupElement
= function OoUiMixinLookupElement( config
) {
5915 // Configuration initialization
5916 config
= $.extend( { highlightFirst
: true }, config
);
5919 this.$overlay
= config
.$overlay
|| this.$element
;
5920 this.lookupMenu
= new OO
.ui
.FloatingMenuSelectWidget( {
5923 $container
: config
.$container
|| this.$element
5926 this.allowSuggestionsWhenEmpty
= config
.allowSuggestionsWhenEmpty
|| false;
5928 this.lookupCache
= {};
5929 this.lookupQuery
= null;
5930 this.lookupRequest
= null;
5931 this.lookupsDisabled
= false;
5932 this.lookupInputFocused
= false;
5933 this.lookupHighlightFirstItem
= config
.highlightFirst
;
5937 focus
: this.onLookupInputFocus
.bind( this ),
5938 blur
: this.onLookupInputBlur
.bind( this ),
5939 mousedown
: this.onLookupInputMouseDown
.bind( this )
5941 this.connect( this, { change
: 'onLookupInputChange' } );
5942 this.lookupMenu
.connect( this, {
5943 toggle
: 'onLookupMenuToggle',
5944 choose
: 'onLookupMenuItemChoose'
5948 this.$element
.addClass( 'oo-ui-lookupElement' );
5949 this.lookupMenu
.$element
.addClass( 'oo-ui-lookupElement-menu' );
5950 this.$overlay
.append( this.lookupMenu
.$element
);
5956 * Handle input focus event.
5959 * @param {jQuery.Event} e Input focus event
5961 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputFocus = function () {
5962 this.lookupInputFocused
= true;
5963 this.populateLookupMenu();
5967 * Handle input blur event.
5970 * @param {jQuery.Event} e Input blur event
5972 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputBlur = function () {
5973 this.closeLookupMenu();
5974 this.lookupInputFocused
= false;
5978 * Handle input mouse down event.
5981 * @param {jQuery.Event} e Input mouse down event
5983 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputMouseDown = function () {
5984 // Only open the menu if the input was already focused.
5985 // This way we allow the user to open the menu again after closing it with Esc
5986 // by clicking in the input. Opening (and populating) the menu when initially
5987 // clicking into the input is handled by the focus handler.
5988 if ( this.lookupInputFocused
&& !this.lookupMenu
.isVisible() ) {
5989 this.populateLookupMenu();
5994 * Handle input change event.
5997 * @param {string} value New input value
5999 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputChange = function () {
6000 if ( this.lookupInputFocused
) {
6001 this.populateLookupMenu();
6006 * Handle the lookup menu being shown/hidden.
6009 * @param {boolean} visible Whether the lookup menu is now visible.
6011 OO
.ui
.mixin
.LookupElement
.prototype.onLookupMenuToggle = function ( visible
) {
6013 // When the menu is hidden, abort any active request and clear the menu.
6014 // This has to be done here in addition to closeLookupMenu(), because
6015 // MenuSelectWidget will close itself when the user presses Esc.
6016 this.abortLookupRequest();
6017 this.lookupMenu
.clearItems();
6022 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
6025 * @param {OO.ui.MenuOptionWidget} item Selected item
6027 OO
.ui
.mixin
.LookupElement
.prototype.onLookupMenuItemChoose = function ( item
) {
6028 this.setValue( item
.getData() );
6035 * @return {OO.ui.FloatingMenuSelectWidget}
6037 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenu = function () {
6038 return this.lookupMenu
;
6042 * Disable or re-enable lookups.
6044 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
6046 * @param {boolean} disabled Disable lookups
6048 OO
.ui
.mixin
.LookupElement
.prototype.setLookupsDisabled = function ( disabled
) {
6049 this.lookupsDisabled
= !!disabled
;
6053 * Open the menu. If there are no entries in the menu, this does nothing.
6058 OO
.ui
.mixin
.LookupElement
.prototype.openLookupMenu = function () {
6059 if ( !this.lookupMenu
.isEmpty() ) {
6060 this.lookupMenu
.toggle( true );
6066 * Close the menu, empty it, and abort any pending request.
6071 OO
.ui
.mixin
.LookupElement
.prototype.closeLookupMenu = function () {
6072 this.lookupMenu
.toggle( false );
6073 this.abortLookupRequest();
6074 this.lookupMenu
.clearItems();
6079 * Request menu items based on the input's current value, and when they arrive,
6080 * populate the menu with these items and show the menu.
6082 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
6087 OO
.ui
.mixin
.LookupElement
.prototype.populateLookupMenu = function () {
6089 value
= this.getValue();
6091 if ( this.lookupsDisabled
|| this.isReadOnly() ) {
6095 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
6096 if ( !this.allowSuggestionsWhenEmpty
&& value
=== '' ) {
6097 this.closeLookupMenu();
6098 // Skip population if there is already a request pending for the current value
6099 } else if ( value
!== this.lookupQuery
) {
6100 this.getLookupMenuItems()
6101 .done( function ( items
) {
6102 widget
.lookupMenu
.clearItems();
6103 if ( items
.length
) {
6107 widget
.initializeLookupMenuSelection();
6109 widget
.lookupMenu
.toggle( false );
6112 .fail( function () {
6113 widget
.lookupMenu
.clearItems();
6121 * Highlight the first selectable item in the menu, if configured.
6126 OO
.ui
.mixin
.LookupElement
.prototype.initializeLookupMenuSelection = function () {
6127 if ( this.lookupHighlightFirstItem
&& !this.lookupMenu
.getSelectedItem() ) {
6128 this.lookupMenu
.highlightItem( this.lookupMenu
.getFirstSelectableItem() );
6133 * Get lookup menu items for the current query.
6136 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
6137 * the done event. If the request was aborted to make way for a subsequent request, this promise
6138 * will not be rejected: it will remain pending forever.
6140 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenuItems = function () {
6142 value
= this.getValue(),
6143 deferred
= $.Deferred(),
6146 this.abortLookupRequest();
6147 if ( Object
.prototype.hasOwnProperty
.call( this.lookupCache
, value
) ) {
6148 deferred
.resolve( this.getLookupMenuOptionsFromData( this.lookupCache
[ value
] ) );
6151 this.lookupQuery
= value
;
6152 ourRequest
= this.lookupRequest
= this.getLookupRequest();
6154 .always( function () {
6155 // We need to pop pending even if this is an old request, otherwise
6156 // the widget will remain pending forever.
6157 // TODO: this assumes that an aborted request will fail or succeed soon after
6158 // being aborted, or at least eventually. It would be nice if we could popPending()
6159 // at abort time, but only if we knew that we hadn't already called popPending()
6160 // for that request.
6161 widget
.popPending();
6163 .done( function ( response
) {
6164 // If this is an old request (and aborting it somehow caused it to still succeed),
6165 // ignore its success completely
6166 if ( ourRequest
=== widget
.lookupRequest
) {
6167 widget
.lookupQuery
= null;
6168 widget
.lookupRequest
= null;
6169 widget
.lookupCache
[ value
] = widget
.getLookupCacheDataFromResponse( response
);
6170 deferred
.resolve( widget
.getLookupMenuOptionsFromData( widget
.lookupCache
[ value
] ) );
6173 .fail( function () {
6174 // If this is an old request (or a request failing because it's being aborted),
6175 // ignore its failure completely
6176 if ( ourRequest
=== widget
.lookupRequest
) {
6177 widget
.lookupQuery
= null;
6178 widget
.lookupRequest
= null;
6183 return deferred
.promise();
6187 * Abort the currently pending lookup request, if any.
6191 OO
.ui
.mixin
.LookupElement
.prototype.abortLookupRequest = function () {
6192 var oldRequest
= this.lookupRequest
;
6194 // First unset this.lookupRequest to the fail handler will notice
6195 // that the request is no longer current
6196 this.lookupRequest
= null;
6197 this.lookupQuery
= null;
6203 * Get a new request object of the current lookup query value.
6207 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
6209 OO
.ui
.mixin
.LookupElement
.prototype.getLookupRequest = function () {
6210 // Stub, implemented in subclass
6215 * Pre-process data returned by the request from #getLookupRequest.
6217 * The return value of this function will be cached, and any further queries for the given value
6218 * will use the cache rather than doing API requests.
6222 * @param {Mixed} response Response from server
6223 * @return {Mixed} Cached result data
6225 OO
.ui
.mixin
.LookupElement
.prototype.getLookupCacheDataFromResponse = function () {
6226 // Stub, implemented in subclass
6231 * Get a list of menu option widgets from the (possibly cached) data returned by
6232 * #getLookupCacheDataFromResponse.
6236 * @param {Mixed} data Cached result data, usually an array
6237 * @return {OO.ui.MenuOptionWidget[]} Menu items
6239 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenuOptionsFromData = function () {
6240 // Stub, implemented in subclass
6245 * Set the read-only state of the widget.
6247 * This will also disable/enable the lookups functionality.
6249 * @param {boolean} readOnly Make input read-only
6252 OO
.ui
.mixin
.LookupElement
.prototype.setReadOnly = function ( readOnly
) {
6254 // Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget
6255 OO
.ui
.TextInputWidget
.prototype.setReadOnly
.call( this, readOnly
);
6257 // During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor
6258 if ( this.isReadOnly() && this.lookupMenu
) {
6259 this.closeLookupMenu();
6266 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
6267 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
6268 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
6269 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
6275 * @param {Object} [config] Configuration options
6276 * @cfg {Object} [popup] Configuration to pass to popup
6277 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
6279 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
6280 // Configuration initialization
6281 config
= config
|| {};
6284 this.popup
= new OO
.ui
.PopupWidget( $.extend(
6285 { autoClose
: true },
6287 { $autoCloseIgnore
: this.$element
}
6296 * @return {OO.ui.PopupWidget} Popup widget
6298 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
6303 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
6304 * additional functionality to an element created by another class. The class provides
6305 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
6306 * which are used to customize the look and feel of a widget to better describe its
6307 * importance and functionality.
6309 * The library currently contains the following styling flags for general use:
6311 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
6312 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
6313 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
6315 * The flags affect the appearance of the buttons:
6318 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
6319 * var button1 = new OO.ui.ButtonWidget( {
6320 * label: 'Constructive',
6321 * flags: 'constructive'
6323 * var button2 = new OO.ui.ButtonWidget( {
6324 * label: 'Destructive',
6325 * flags: 'destructive'
6327 * var button3 = new OO.ui.ButtonWidget( {
6328 * label: 'Progressive',
6329 * flags: 'progressive'
6331 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
6333 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
6334 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6336 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6342 * @param {Object} [config] Configuration options
6343 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
6344 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
6345 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6346 * @cfg {jQuery} [$flagged] The flagged element. By default,
6347 * the flagged functionality is applied to the element created by the class ($element).
6348 * If a different element is specified, the flagged functionality will be applied to it instead.
6350 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
6351 // Configuration initialization
6352 config
= config
|| {};
6356 this.$flagged
= null;
6359 this.setFlags( config
.flags
);
6360 this.setFlaggedElement( config
.$flagged
|| this.$element
);
6367 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
6368 * parameter contains the name of each modified flag and indicates whether it was
6371 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
6372 * that the flag was added, `false` that the flag was removed.
6378 * Set the flagged element.
6380 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
6381 * If an element is already set, the method will remove the mixin’s effect on that element.
6383 * @param {jQuery} $flagged Element that should be flagged
6385 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
6386 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
6387 return 'oo-ui-flaggedElement-' + flag
;
6390 if ( this.$flagged
) {
6391 this.$flagged
.removeClass( classNames
);
6394 this.$flagged
= $flagged
.addClass( classNames
);
6398 * Check if the specified flag is set.
6400 * @param {string} flag Name of flag
6401 * @return {boolean} The flag is set
6403 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
6404 // This may be called before the constructor, thus before this.flags is set
6405 return this.flags
&& ( flag
in this.flags
);
6409 * Get the names of all flags set.
6411 * @return {string[]} Flag names
6413 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
6414 // This may be called before the constructor, thus before this.flags is set
6415 return Object
.keys( this.flags
|| {} );
6424 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
6425 var flag
, className
,
6428 classPrefix
= 'oo-ui-flaggedElement-';
6430 for ( flag
in this.flags
) {
6431 className
= classPrefix
+ flag
;
6432 changes
[ flag
] = false;
6433 delete this.flags
[ flag
];
6434 remove
.push( className
);
6437 if ( this.$flagged
) {
6438 this.$flagged
.removeClass( remove
.join( ' ' ) );
6441 this.updateThemeClasses();
6442 this.emit( 'flag', changes
);
6448 * Add one or more flags.
6450 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
6451 * or an object keyed by flag name with a boolean value that indicates whether the flag should
6452 * be added (`true`) or removed (`false`).
6456 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
6457 var i
, len
, flag
, className
,
6461 classPrefix
= 'oo-ui-flaggedElement-';
6463 if ( typeof flags
=== 'string' ) {
6464 className
= classPrefix
+ flags
;
6466 if ( !this.flags
[ flags
] ) {
6467 this.flags
[ flags
] = true;
6468 add
.push( className
);
6470 } else if ( Array
.isArray( flags
) ) {
6471 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
6473 className
= classPrefix
+ flag
;
6475 if ( !this.flags
[ flag
] ) {
6476 changes
[ flag
] = true;
6477 this.flags
[ flag
] = true;
6478 add
.push( className
);
6481 } else if ( OO
.isPlainObject( flags
) ) {
6482 for ( flag
in flags
) {
6483 className
= classPrefix
+ flag
;
6484 if ( flags
[ flag
] ) {
6486 if ( !this.flags
[ flag
] ) {
6487 changes
[ flag
] = true;
6488 this.flags
[ flag
] = true;
6489 add
.push( className
);
6493 if ( this.flags
[ flag
] ) {
6494 changes
[ flag
] = false;
6495 delete this.flags
[ flag
];
6496 remove
.push( className
);
6502 if ( this.$flagged
) {
6504 .addClass( add
.join( ' ' ) )
6505 .removeClass( remove
.join( ' ' ) );
6508 this.updateThemeClasses();
6509 this.emit( 'flag', changes
);
6515 * TitledElement is mixed into other classes to provide a `title` attribute.
6516 * Titles are rendered by the browser and are made visible when the user moves
6517 * the mouse over the element. Titles are not visible on touch devices.
6520 * // TitledElement provides a 'title' attribute to the
6521 * // ButtonWidget class
6522 * var button = new OO.ui.ButtonWidget( {
6523 * label: 'Button with Title',
6524 * title: 'I am a button'
6526 * $( 'body' ).append( button.$element );
6532 * @param {Object} [config] Configuration options
6533 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6534 * If this config is omitted, the title functionality is applied to $element, the
6535 * element created by the class.
6536 * @cfg {string|Function} [title] The title text or a function that returns text. If
6537 * this config is omitted, the value of the {@link #static-title static title} property is used.
6539 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
6540 // Configuration initialization
6541 config
= config
|| {};
6544 this.$titled
= null;
6548 this.setTitle( config
.title
|| this.constructor.static.title
);
6549 this.setTitledElement( config
.$titled
|| this.$element
);
6554 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
6556 /* Static Properties */
6559 * The title text, a function that returns text, or `null` for no title. The value of the static property
6560 * is overridden if the #title config option is used.
6564 * @property {string|Function|null}
6566 OO
.ui
.mixin
.TitledElement
.static.title
= null;
6571 * Set the titled element.
6573 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6574 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6576 * @param {jQuery} $titled Element that should use the 'titled' functionality
6578 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
6579 if ( this.$titled
) {
6580 this.$titled
.removeAttr( 'title' );
6583 this.$titled
= $titled
;
6585 this.$titled
.attr( 'title', this.title
);
6592 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6595 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
6596 title
= typeof title
=== 'string' ? OO
.ui
.resolveMsg( title
) : null;
6598 if ( this.title
!== title
) {
6599 if ( this.$titled
) {
6600 if ( title
!== null ) {
6601 this.$titled
.attr( 'title', title
);
6603 this.$titled
.removeAttr( 'title' );
6615 * @return {string} Title string
6617 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
6622 * Element that can be automatically clipped to visible boundaries.
6624 * Whenever the element's natural height changes, you have to call
6625 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
6626 * clipping correctly.
6628 * The dimensions of #$clippableContainer will be compared to the boundaries of the
6629 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
6630 * then #$clippable will be given a fixed reduced height and/or width and will be made
6631 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
6632 * but you can build a static footer by setting #$clippableContainer to an element that contains
6633 * #$clippable and the footer.
6639 * @param {Object} [config] Configuration options
6640 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
6641 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
6642 * omit to use #$clippable
6644 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
6645 // Configuration initialization
6646 config
= config
|| {};
6649 this.$clippable
= null;
6650 this.$clippableContainer
= null;
6651 this.clipping
= false;
6652 this.clippedHorizontally
= false;
6653 this.clippedVertically
= false;
6654 this.$clippableScrollableContainer
= null;
6655 this.$clippableScroller
= null;
6656 this.$clippableWindow
= null;
6657 this.idealWidth
= null;
6658 this.idealHeight
= null;
6659 this.onClippableScrollHandler
= this.clip
.bind( this );
6660 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
6663 if ( config
.$clippableContainer
) {
6664 this.setClippableContainer( config
.$clippableContainer
);
6666 this.setClippableElement( config
.$clippable
|| this.$element
);
6672 * Set clippable element.
6674 * If an element is already set, it will be cleaned up before setting up the new element.
6676 * @param {jQuery} $clippable Element to make clippable
6678 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
6679 if ( this.$clippable
) {
6680 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
6681 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6682 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6685 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
6690 * Set clippable container.
6692 * This is the container that will be measured when deciding whether to clip. When clipping,
6693 * #$clippable will be resized in order to keep the clippable container fully visible.
6695 * If the clippable container is unset, #$clippable will be used.
6697 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
6699 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableContainer = function ( $clippableContainer
) {
6700 this.$clippableContainer
= $clippableContainer
;
6701 if ( this.$clippable
) {
6709 * Do not turn clipping on until after the element is attached to the DOM and visible.
6711 * @param {boolean} [clipping] Enable clipping, omit to toggle
6714 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
6715 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
6717 if ( this.clipping
!== clipping
) {
6718 this.clipping
= clipping
;
6720 this.$clippableScrollableContainer
= $( this.getClosestScrollableElementContainer() );
6721 // If the clippable container is the root, we have to listen to scroll events and check
6722 // jQuery.scrollTop on the window because of browser inconsistencies
6723 this.$clippableScroller
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
6724 $( OO
.ui
.Element
.static.getWindow( this.$clippableScrollableContainer
) ) :
6725 this.$clippableScrollableContainer
;
6726 this.$clippableScroller
.on( 'scroll', this.onClippableScrollHandler
);
6727 this.$clippableWindow
= $( this.getElementWindow() )
6728 .on( 'resize', this.onClippableWindowResizeHandler
);
6729 // Initial clip after visible
6732 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6733 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6735 this.$clippableScrollableContainer
= null;
6736 this.$clippableScroller
.off( 'scroll', this.onClippableScrollHandler
);
6737 this.$clippableScroller
= null;
6738 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
6739 this.$clippableWindow
= null;
6747 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6749 * @return {boolean} Element will be clipped to the visible area
6751 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
6752 return this.clipping
;
6756 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6758 * @return {boolean} Part of the element is being clipped
6760 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
6761 return this.clippedHorizontally
|| this.clippedVertically
;
6765 * Check if the right of the element is being clipped by the nearest scrollable container.
6767 * @return {boolean} Part of the element is being clipped
6769 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
6770 return this.clippedHorizontally
;
6774 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6776 * @return {boolean} Part of the element is being clipped
6778 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
6779 return this.clippedVertically
;
6783 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6785 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6786 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6788 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
6789 this.idealWidth
= width
;
6790 this.idealHeight
= height
;
6792 if ( !this.clipping
) {
6793 // Update dimensions
6794 this.$clippable
.css( { width
: width
, height
: height
} );
6796 // While clipping, idealWidth and idealHeight are not considered
6800 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6801 * the element's natural height changes.
6803 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6804 * overlapped by, the visible area of the nearest scrollable container.
6808 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
6809 var $container
, extraHeight
, extraWidth
, ccOffset
,
6810 $scrollableContainer
, scOffset
, scHeight
, scWidth
,
6811 ccWidth
, scrollerIsWindow
, scrollTop
, scrollLeft
,
6812 desiredWidth
, desiredHeight
, allotedWidth
, allotedHeight
,
6813 naturalWidth
, naturalHeight
, clipWidth
, clipHeight
,
6814 buffer
= 7; // Chosen by fair dice roll
6816 if ( !this.clipping
) {
6817 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
6821 $container
= this.$clippableContainer
|| this.$clippable
;
6822 extraHeight
= $container
.outerHeight() - this.$clippable
.outerHeight();
6823 extraWidth
= $container
.outerWidth() - this.$clippable
.outerWidth();
6824 ccOffset
= $container
.offset();
6825 $scrollableContainer
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
6826 this.$clippableWindow
: this.$clippableScrollableContainer
;
6827 scOffset
= $scrollableContainer
.offset() || { top
: 0, left
: 0 };
6828 scHeight
= $scrollableContainer
.innerHeight() - buffer
;
6829 scWidth
= $scrollableContainer
.innerWidth() - buffer
;
6830 ccWidth
= $container
.outerWidth() + buffer
;
6831 scrollerIsWindow
= this.$clippableScroller
[ 0 ] === this.$clippableWindow
[ 0 ];
6832 scrollTop
= scrollerIsWindow
? this.$clippableScroller
.scrollTop() : 0;
6833 scrollLeft
= scrollerIsWindow
? this.$clippableScroller
.scrollLeft() : 0;
6834 desiredWidth
= ccOffset
.left
< 0 ?
6835 ccWidth
+ ccOffset
.left
:
6836 ( scOffset
.left
+ scrollLeft
+ scWidth
) - ccOffset
.left
;
6837 desiredHeight
= ( scOffset
.top
+ scrollTop
+ scHeight
) - ccOffset
.top
;
6838 allotedWidth
= desiredWidth
- extraWidth
;
6839 allotedHeight
= desiredHeight
- extraHeight
;
6840 naturalWidth
= this.$clippable
.prop( 'scrollWidth' );
6841 naturalHeight
= this.$clippable
.prop( 'scrollHeight' );
6842 clipWidth
= allotedWidth
< naturalWidth
;
6843 clipHeight
= allotedHeight
< naturalHeight
;
6846 this.$clippable
.css( { overflowX
: 'scroll', width
: Math
.max( 0, allotedWidth
) } );
6848 this.$clippable
.css( { width
: this.idealWidth
? this.idealWidth
- extraWidth
: '', overflowX
: '' } );
6851 this.$clippable
.css( { overflowY
: 'scroll', height
: Math
.max( 0, allotedHeight
) } );
6853 this.$clippable
.css( { height
: this.idealHeight
? this.idealHeight
- extraHeight
: '', overflowY
: '' } );
6856 // If we stopped clipping in at least one of the dimensions
6857 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
6858 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6861 this.clippedHorizontally
= clipWidth
;
6862 this.clippedVertically
= clipHeight
;
6868 * Element that will stick under a specified container, even when it is inserted elsewhere in the
6869 * document (for example, in a OO.ui.Window's $overlay).
6871 * The elements's position is automatically calculated and maintained when window is resized or the
6872 * page is scrolled. If you reposition the container manually, you have to call #position to make
6873 * sure the element is still placed correctly.
6875 * As positioning is only possible when both the element and the container are attached to the DOM
6876 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
6877 * the #toggle method to display a floating popup, for example.
6883 * @param {Object} [config] Configuration options
6884 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
6885 * @cfg {jQuery} [$floatableContainer] Node to position below
6887 OO
.ui
.mixin
.FloatableElement
= function OoUiMixinFloatableElement( config
) {
6888 // Configuration initialization
6889 config
= config
|| {};
6892 this.$floatable
= null;
6893 this.$floatableContainer
= null;
6894 this.$floatableWindow
= null;
6895 this.$floatableClosestScrollable
= null;
6896 this.onFloatableScrollHandler
= this.position
.bind( this );
6897 this.onFloatableWindowResizeHandler
= this.position
.bind( this );
6900 this.setFloatableContainer( config
.$floatableContainer
);
6901 this.setFloatableElement( config
.$floatable
|| this.$element
);
6907 * Set floatable element.
6909 * If an element is already set, it will be cleaned up before setting up the new element.
6911 * @param {jQuery} $floatable Element to make floatable
6913 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableElement = function ( $floatable
) {
6914 if ( this.$floatable
) {
6915 this.$floatable
.removeClass( 'oo-ui-floatableElement-floatable' );
6916 this.$floatable
.css( { left
: '', top
: '' } );
6919 this.$floatable
= $floatable
.addClass( 'oo-ui-floatableElement-floatable' );
6924 * Set floatable container.
6926 * The element will be always positioned under the specified container.
6928 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
6930 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableContainer = function ( $floatableContainer
) {
6931 this.$floatableContainer
= $floatableContainer
;
6932 if ( this.$floatable
) {
6938 * Toggle positioning.
6940 * Do not turn positioning on until after the element is attached to the DOM and visible.
6942 * @param {boolean} [positioning] Enable positioning, omit to toggle
6945 OO
.ui
.mixin
.FloatableElement
.prototype.togglePositioning = function ( positioning
) {
6946 var closestScrollableOfContainer
, closestScrollableOfFloatable
;
6948 positioning
= positioning
=== undefined ? !this.positioning
: !!positioning
;
6950 if ( this.positioning
!== positioning
) {
6951 this.positioning
= positioning
;
6953 closestScrollableOfContainer
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatableContainer
[ 0 ] );
6954 closestScrollableOfFloatable
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatable
[ 0 ] );
6955 if ( closestScrollableOfContainer
!== closestScrollableOfFloatable
) {
6956 // If the scrollable is the root, we have to listen to scroll events
6957 // on the window because of browser inconsistencies (or do we? someone should verify this)
6958 if ( $( closestScrollableOfContainer
).is( 'html, body' ) ) {
6959 closestScrollableOfContainer
= OO
.ui
.Element
.static.getWindow( closestScrollableOfContainer
);
6963 if ( positioning
) {
6964 this.$floatableWindow
= $( this.getElementWindow() );
6965 this.$floatableWindow
.on( 'resize', this.onFloatableWindowResizeHandler
);
6967 if ( closestScrollableOfContainer
!== closestScrollableOfFloatable
) {
6968 this.$floatableClosestScrollable
= $( closestScrollableOfContainer
);
6969 this.$floatableClosestScrollable
.on( 'scroll', this.onFloatableScrollHandler
);
6972 // Initial position after visible
6975 if ( this.$floatableWindow
) {
6976 this.$floatableWindow
.off( 'resize', this.onFloatableWindowResizeHandler
);
6977 this.$floatableWindow
= null;
6980 if ( this.$floatableClosestScrollable
) {
6981 this.$floatableClosestScrollable
.off( 'scroll', this.onFloatableScrollHandler
);
6982 this.$floatableClosestScrollable
= null;
6985 this.$floatable
.css( { left
: '', top
: '' } );
6993 * Position the floatable below its container.
6995 * This should only be done when both of them are attached to the DOM and visible.
6999 OO
.ui
.mixin
.FloatableElement
.prototype.position = function () {
7002 if ( !this.positioning
) {
7006 pos
= OO
.ui
.Element
.static.getRelativePosition( this.$floatableContainer
, this.$floatable
.offsetParent() );
7008 // Position under container
7009 pos
.top
+= this.$floatableContainer
.height();
7010 this.$floatable
.css( pos
);
7012 // We updated the position, so re-evaluate the clipping state.
7013 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
7014 // will not notice the need to update itself.)
7015 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
7016 // it not listen to the right events in the right places?
7025 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
7026 * Accesskeys allow an user to go to a specific element by using
7027 * a shortcut combination of a browser specific keys + the key
7031 * // AccessKeyedElement provides an 'accesskey' attribute to the
7032 * // ButtonWidget class
7033 * var button = new OO.ui.ButtonWidget( {
7034 * label: 'Button with Accesskey',
7037 * $( 'body' ).append( button.$element );
7043 * @param {Object} [config] Configuration options
7044 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
7045 * If this config is omitted, the accesskey functionality is applied to $element, the
7046 * element created by the class.
7047 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
7048 * this config is omitted, no accesskey will be added.
7050 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
7051 // Configuration initialization
7052 config
= config
|| {};
7055 this.$accessKeyed
= null;
7056 this.accessKey
= null;
7059 this.setAccessKey( config
.accessKey
|| null );
7060 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
7065 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
7067 /* Static Properties */
7070 * The access key, a function that returns a key, or `null` for no accesskey.
7074 * @property {string|Function|null}
7076 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
7081 * Set the accesskeyed element.
7083 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
7084 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
7086 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
7088 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
7089 if ( this.$accessKeyed
) {
7090 this.$accessKeyed
.removeAttr( 'accesskey' );
7093 this.$accessKeyed
= $accessKeyed
;
7094 if ( this.accessKey
) {
7095 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
7102 * @param {string|Function|null} accesskey Key, a function that returns a key, or `null` for no accesskey
7105 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
7106 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
7108 if ( this.accessKey
!== accessKey
) {
7109 if ( this.$accessKeyed
) {
7110 if ( accessKey
!== null ) {
7111 this.$accessKeyed
.attr( 'accesskey', accessKey
);
7113 this.$accessKeyed
.removeAttr( 'accesskey' );
7116 this.accessKey
= accessKey
;
7125 * @return {string} accessKey string
7127 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
7128 return this.accessKey
;
7132 * Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute {@link OO.ui.Toolbar toolbars}.
7133 * Each tool is configured with a static name, title, and icon and is customized with the command to carry
7134 * out when the tool is selected. Tools must also be registered with a {@link OO.ui.ToolFactory tool factory},
7135 * which creates the tools on demand.
7137 * Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup},
7138 * {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which determine how
7139 * the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an example.
7141 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
7142 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7146 * @extends OO.ui.Widget
7147 * @mixins OO.ui.mixin.IconElement
7148 * @mixins OO.ui.mixin.FlaggedElement
7149 * @mixins OO.ui.mixin.TabIndexedElement
7152 * @param {OO.ui.ToolGroup} toolGroup
7153 * @param {Object} [config] Configuration options
7154 * @cfg {string|Function} [title] Title text or a function that returns text. If this config is omitted, the value of
7155 * the {@link #static-title static title} property is used.
7157 * The title is used in different ways depending on the type of toolgroup that contains the tool. The
7158 * 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
7159 * part of a {@link OO.ui.ListToolGroup list} or {@link OO.ui.MenuToolGroup menu} toolgroup.
7161 * For bar toolgroups, a description of the accelerator key is appended to the title if an accelerator key
7162 * is associated with an action by the same name as the tool and accelerator functionality has been added to the application.
7163 * To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method.
7165 OO
.ui
.Tool
= function OoUiTool( toolGroup
, config
) {
7166 // Allow passing positional parameters inside the config object
7167 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
7169 toolGroup
= config
.toolGroup
;
7172 // Configuration initialization
7173 config
= config
|| {};
7175 // Parent constructor
7176 OO
.ui
.Tool
.parent
.call( this, config
);
7179 this.toolGroup
= toolGroup
;
7180 this.toolbar
= this.toolGroup
.getToolbar();
7181 this.active
= false;
7182 this.$title
= $( '<span>' );
7183 this.$accel
= $( '<span>' );
7184 this.$link
= $( '<a>' );
7187 // Mixin constructors
7188 OO
.ui
.mixin
.IconElement
.call( this, config
);
7189 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
7190 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$link
} ) );
7193 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
7196 this.$title
.addClass( 'oo-ui-tool-title' );
7198 .addClass( 'oo-ui-tool-accel' )
7200 // This may need to be changed if the key names are ever localized,
7201 // but for now they are essentially written in English
7206 .addClass( 'oo-ui-tool-link' )
7207 .append( this.$icon
, this.$title
, this.$accel
)
7208 .attr( 'role', 'button' );
7210 .data( 'oo-ui-tool', this )
7212 'oo-ui-tool ' + 'oo-ui-tool-name-' +
7213 this.constructor.static.name
.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
7215 .toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel
)
7216 .append( this.$link
);
7217 this.setTitle( config
.title
|| this.constructor.static.title
);
7222 OO
.inheritClass( OO
.ui
.Tool
, OO
.ui
.Widget
);
7223 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.IconElement
);
7224 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.FlaggedElement
);
7225 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.TabIndexedElement
);
7227 /* Static Properties */
7233 OO
.ui
.Tool
.static.tagName
= 'span';
7236 * Symbolic name of tool.
7238 * The symbolic name is used internally to register the tool with a {@link OO.ui.ToolFactory ToolFactory}. It can
7239 * also be used when adding tools to toolgroups.
7244 * @property {string}
7246 OO
.ui
.Tool
.static.name
= '';
7249 * Symbolic name of the group.
7251 * The group name is used to associate tools with each other so that they can be selected later by
7252 * a {@link OO.ui.ToolGroup toolgroup}.
7257 * @property {string}
7259 OO
.ui
.Tool
.static.group
= '';
7262 * 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.
7267 * @property {string|Function}
7269 OO
.ui
.Tool
.static.title
= '';
7272 * Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup.
7273 * Normally only the icon is displayed, or only the label if no icon is given.
7277 * @property {boolean}
7279 OO
.ui
.Tool
.static.displayBothIconAndLabel
= false;
7282 * Add tool to catch-all groups automatically.
7284 * A catch-all group, which contains all tools that do not currently belong to a toolgroup,
7285 * can be included in a toolgroup using the wildcard selector, an asterisk (*).
7289 * @property {boolean}
7291 OO
.ui
.Tool
.static.autoAddToCatchall
= true;
7294 * Add tool to named groups automatically.
7296 * By default, tools that are configured with a static ‘group’ property are added
7297 * to that group and will be selected when the symbolic name of the group is specified (e.g., when
7298 * toolgroups include tools by group name).
7301 * @property {boolean}
7304 OO
.ui
.Tool
.static.autoAddToGroup
= true;
7307 * Check if this tool is compatible with given data.
7309 * This is a stub that can be overriden to provide support for filtering tools based on an
7310 * arbitrary piece of information (e.g., where the cursor is in a document). The implementation
7311 * must also call this method so that the compatibility check can be performed.
7315 * @param {Mixed} data Data to check
7316 * @return {boolean} Tool can be used with data
7318 OO
.ui
.Tool
.static.isCompatibleWith = function () {
7325 * Handle the toolbar state being updated.
7327 * This is an abstract method that must be overridden in a concrete subclass.
7332 OO
.ui
.Tool
.prototype.onUpdateState = function () {
7334 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
7339 * Handle the tool being selected.
7341 * This is an abstract method that must be overridden in a concrete subclass.
7346 OO
.ui
.Tool
.prototype.onSelect = function () {
7348 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
7353 * Check if the tool is active.
7355 * Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed
7356 * with the #setActive method. Additional CSS is applied to the tool to reflect the active state.
7358 * @return {boolean} Tool is active
7360 OO
.ui
.Tool
.prototype.isActive = function () {
7365 * Make the tool appear active or inactive.
7367 * This method should be called within #onSelect or #onUpdateState event handlers to make the tool
7368 * appear pressed or not.
7370 * @param {boolean} state Make tool appear active
7372 OO
.ui
.Tool
.prototype.setActive = function ( state
) {
7373 this.active
= !!state
;
7374 if ( this.active
) {
7375 this.$element
.addClass( 'oo-ui-tool-active' );
7377 this.$element
.removeClass( 'oo-ui-tool-active' );
7382 * Set the tool #title.
7384 * @param {string|Function} title Title text or a function that returns text
7387 OO
.ui
.Tool
.prototype.setTitle = function ( title
) {
7388 this.title
= OO
.ui
.resolveMsg( title
);
7394 * Get the tool #title.
7396 * @return {string} Title text
7398 OO
.ui
.Tool
.prototype.getTitle = function () {
7403 * Get the tool's symbolic name.
7405 * @return {string} Symbolic name of tool
7407 OO
.ui
.Tool
.prototype.getName = function () {
7408 return this.constructor.static.name
;
7414 OO
.ui
.Tool
.prototype.updateTitle = function () {
7415 var titleTooltips
= this.toolGroup
.constructor.static.titleTooltips
,
7416 accelTooltips
= this.toolGroup
.constructor.static.accelTooltips
,
7417 accel
= this.toolbar
.getToolAccelerator( this.constructor.static.name
),
7420 this.$title
.text( this.title
);
7421 this.$accel
.text( accel
);
7423 if ( titleTooltips
&& typeof this.title
=== 'string' && this.title
.length
) {
7424 tooltipParts
.push( this.title
);
7426 if ( accelTooltips
&& typeof accel
=== 'string' && accel
.length
) {
7427 tooltipParts
.push( accel
);
7429 if ( tooltipParts
.length
) {
7430 this.$link
.attr( 'title', tooltipParts
.join( ' ' ) );
7432 this.$link
.removeAttr( 'title' );
7439 * Destroying the tool removes all event handlers and the tool’s DOM elements.
7440 * Call this method whenever you are done using a tool.
7442 OO
.ui
.Tool
.prototype.destroy = function () {
7443 this.toolbar
.disconnect( this );
7444 this.$element
.remove();
7448 * Toolbars are complex interface components that permit users to easily access a variety
7449 * of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional commands that are
7450 * part of the toolbar, but not configured as tools.
7452 * Individual tools are customized and then registered with a {@link OO.ui.ToolFactory tool factory}, which creates
7453 * the tools on demand. Each tool has a symbolic name (used when registering the tool), a title (e.g., ‘Insert
7454 * picture’), and an icon.
7456 * Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be {@link OO.ui.MenuToolGroup menus}
7457 * of tools, {@link OO.ui.ListToolGroup lists} of tools, or a single {@link OO.ui.BarToolGroup bar} of tools.
7458 * The arrangement and order of the toolgroups is customized when the toolbar is set up. Tools can be presented in
7459 * any order, but each can only appear once in the toolbar.
7461 * The following is an example of a basic toolbar.
7464 * // Example of a toolbar
7465 * // Create the toolbar
7466 * var toolFactory = new OO.ui.ToolFactory();
7467 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7468 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7470 * // We will be placing status text in this element when tools are used
7471 * var $area = $( '<p>' ).text( 'Toolbar example' );
7473 * // Define the tools that we're going to place in our toolbar
7475 * // Create a class inheriting from OO.ui.Tool
7476 * function PictureTool() {
7477 * PictureTool.parent.apply( this, arguments );
7479 * OO.inheritClass( PictureTool, OO.ui.Tool );
7480 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7481 * // of 'icon' and 'title' (displayed icon and text).
7482 * PictureTool.static.name = 'picture';
7483 * PictureTool.static.icon = 'picture';
7484 * PictureTool.static.title = 'Insert picture';
7485 * // Defines the action that will happen when this tool is selected (clicked).
7486 * PictureTool.prototype.onSelect = function () {
7487 * $area.text( 'Picture tool clicked!' );
7488 * // Never display this tool as "active" (selected).
7489 * this.setActive( false );
7491 * // Make this tool available in our toolFactory and thus our toolbar
7492 * toolFactory.register( PictureTool );
7494 * // Register two more tools, nothing interesting here
7495 * function SettingsTool() {
7496 * SettingsTool.parent.apply( this, arguments );
7498 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7499 * SettingsTool.static.name = 'settings';
7500 * SettingsTool.static.icon = 'settings';
7501 * SettingsTool.static.title = 'Change settings';
7502 * SettingsTool.prototype.onSelect = function () {
7503 * $area.text( 'Settings tool clicked!' );
7504 * this.setActive( false );
7506 * toolFactory.register( SettingsTool );
7508 * // Register two more tools, nothing interesting here
7509 * function StuffTool() {
7510 * StuffTool.parent.apply( this, arguments );
7512 * OO.inheritClass( StuffTool, OO.ui.Tool );
7513 * StuffTool.static.name = 'stuff';
7514 * StuffTool.static.icon = 'ellipsis';
7515 * StuffTool.static.title = 'More stuff';
7516 * StuffTool.prototype.onSelect = function () {
7517 * $area.text( 'More stuff tool clicked!' );
7518 * this.setActive( false );
7520 * toolFactory.register( StuffTool );
7522 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7523 * // little popup window (a PopupWidget).
7524 * function HelpTool( toolGroup, config ) {
7525 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7530 * this.popup.$body.append( '<p>I am helpful!</p>' );
7532 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7533 * HelpTool.static.name = 'help';
7534 * HelpTool.static.icon = 'help';
7535 * HelpTool.static.title = 'Help';
7536 * toolFactory.register( HelpTool );
7538 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7539 * // used once (but not all defined tools must be used).
7542 * // 'bar' tool groups display tools' icons only, side-by-side.
7544 * include: [ 'picture', 'help' ]
7547 * // 'list' tool groups display both the titles and icons, in a dropdown list.
7549 * indicator: 'down',
7551 * include: [ 'settings', 'stuff' ]
7553 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
7554 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here,
7555 * // since it's more complicated to use. (See the next example snippet on this page.)
7558 * // Create some UI around the toolbar and place it in the document
7559 * var frame = new OO.ui.PanelLayout( {
7563 * var contentFrame = new OO.ui.PanelLayout( {
7567 * frame.$element.append(
7569 * contentFrame.$element.append( $area )
7571 * $( 'body' ).append( frame.$element );
7573 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7575 * toolbar.initialize();
7577 * The following example extends the previous one to illustrate 'menu' toolgroups and the usage of
7578 * 'updateState' event.
7581 * // Create the toolbar
7582 * var toolFactory = new OO.ui.ToolFactory();
7583 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7584 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7586 * // We will be placing status text in this element when tools are used
7587 * var $area = $( '<p>' ).text( 'Toolbar example' );
7589 * // Define the tools that we're going to place in our toolbar
7591 * // Create a class inheriting from OO.ui.Tool
7592 * function PictureTool() {
7593 * PictureTool.parent.apply( this, arguments );
7595 * OO.inheritClass( PictureTool, OO.ui.Tool );
7596 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7597 * // of 'icon' and 'title' (displayed icon and text).
7598 * PictureTool.static.name = 'picture';
7599 * PictureTool.static.icon = 'picture';
7600 * PictureTool.static.title = 'Insert picture';
7601 * // Defines the action that will happen when this tool is selected (clicked).
7602 * PictureTool.prototype.onSelect = function () {
7603 * $area.text( 'Picture tool clicked!' );
7604 * // Never display this tool as "active" (selected).
7605 * this.setActive( false );
7607 * // The toolbar can be synchronized with the state of some external stuff, like a text
7608 * // editor's editing area, highlighting the tools (e.g. a 'bold' tool would be shown as active
7609 * // when the text cursor was inside bolded text). Here we simply disable this feature.
7610 * PictureTool.prototype.onUpdateState = function () {
7612 * // Make this tool available in our toolFactory and thus our toolbar
7613 * toolFactory.register( PictureTool );
7615 * // Register two more tools, nothing interesting here
7616 * function SettingsTool() {
7617 * SettingsTool.parent.apply( this, arguments );
7618 * this.reallyActive = false;
7620 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7621 * SettingsTool.static.name = 'settings';
7622 * SettingsTool.static.icon = 'settings';
7623 * SettingsTool.static.title = 'Change settings';
7624 * SettingsTool.prototype.onSelect = function () {
7625 * $area.text( 'Settings tool clicked!' );
7626 * // Toggle the active state on each click
7627 * this.reallyActive = !this.reallyActive;
7628 * this.setActive( this.reallyActive );
7629 * // To update the menu label
7630 * this.toolbar.emit( 'updateState' );
7632 * SettingsTool.prototype.onUpdateState = function () {
7634 * toolFactory.register( SettingsTool );
7636 * // Register two more tools, nothing interesting here
7637 * function StuffTool() {
7638 * StuffTool.parent.apply( this, arguments );
7639 * this.reallyActive = false;
7641 * OO.inheritClass( StuffTool, OO.ui.Tool );
7642 * StuffTool.static.name = 'stuff';
7643 * StuffTool.static.icon = 'ellipsis';
7644 * StuffTool.static.title = 'More stuff';
7645 * StuffTool.prototype.onSelect = function () {
7646 * $area.text( 'More stuff tool clicked!' );
7647 * // Toggle the active state on each click
7648 * this.reallyActive = !this.reallyActive;
7649 * this.setActive( this.reallyActive );
7650 * // To update the menu label
7651 * this.toolbar.emit( 'updateState' );
7653 * StuffTool.prototype.onUpdateState = function () {
7655 * toolFactory.register( StuffTool );
7657 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7658 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
7659 * function HelpTool( toolGroup, config ) {
7660 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7665 * this.popup.$body.append( '<p>I am helpful!</p>' );
7667 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7668 * HelpTool.static.name = 'help';
7669 * HelpTool.static.icon = 'help';
7670 * HelpTool.static.title = 'Help';
7671 * toolFactory.register( HelpTool );
7673 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7674 * // used once (but not all defined tools must be used).
7677 * // 'bar' tool groups display tools' icons only, side-by-side.
7679 * include: [ 'picture', 'help' ]
7682 * // 'menu' tool groups display both the titles and icons, in a dropdown menu.
7683 * // Menu label indicates which items are selected.
7685 * indicator: 'down',
7686 * include: [ 'settings', 'stuff' ]
7690 * // Create some UI around the toolbar and place it in the document
7691 * var frame = new OO.ui.PanelLayout( {
7695 * var contentFrame = new OO.ui.PanelLayout( {
7699 * frame.$element.append(
7701 * contentFrame.$element.append( $area )
7703 * $( 'body' ).append( frame.$element );
7705 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7707 * toolbar.initialize();
7708 * toolbar.emit( 'updateState' );
7711 * @extends OO.ui.Element
7712 * @mixins OO.EventEmitter
7713 * @mixins OO.ui.mixin.GroupElement
7716 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
7717 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups
7718 * @param {Object} [config] Configuration options
7719 * @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are included
7720 * in the toolbar, but are not configured as tools. By default, actions are displayed on the right side of
7722 * @cfg {boolean} [shadow] Add a shadow below the toolbar.
7724 OO
.ui
.Toolbar
= function OoUiToolbar( toolFactory
, toolGroupFactory
, config
) {
7725 // Allow passing positional parameters inside the config object
7726 if ( OO
.isPlainObject( toolFactory
) && config
=== undefined ) {
7727 config
= toolFactory
;
7728 toolFactory
= config
.toolFactory
;
7729 toolGroupFactory
= config
.toolGroupFactory
;
7732 // Configuration initialization
7733 config
= config
|| {};
7735 // Parent constructor
7736 OO
.ui
.Toolbar
.parent
.call( this, config
);
7738 // Mixin constructors
7739 OO
.EventEmitter
.call( this );
7740 OO
.ui
.mixin
.GroupElement
.call( this, config
);
7743 this.toolFactory
= toolFactory
;
7744 this.toolGroupFactory
= toolGroupFactory
;
7747 this.$bar
= $( '<div>' );
7748 this.$actions
= $( '<div>' );
7749 this.initialized
= false;
7750 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
7754 .add( this.$bar
).add( this.$group
).add( this.$actions
)
7755 .on( 'mousedown keydown', this.onPointerDown
.bind( this ) );
7758 this.$group
.addClass( 'oo-ui-toolbar-tools' );
7759 if ( config
.actions
) {
7760 this.$bar
.append( this.$actions
.addClass( 'oo-ui-toolbar-actions' ) );
7763 .addClass( 'oo-ui-toolbar-bar' )
7764 .append( this.$group
, '<div style="clear:both"></div>' );
7765 if ( config
.shadow
) {
7766 this.$bar
.append( '<div class="oo-ui-toolbar-shadow"></div>' );
7768 this.$element
.addClass( 'oo-ui-toolbar' ).append( this.$bar
);
7773 OO
.inheritClass( OO
.ui
.Toolbar
, OO
.ui
.Element
);
7774 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.EventEmitter
);
7775 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.ui
.mixin
.GroupElement
);
7780 * Get the tool factory.
7782 * @return {OO.ui.ToolFactory} Tool factory
7784 OO
.ui
.Toolbar
.prototype.getToolFactory = function () {
7785 return this.toolFactory
;
7789 * Get the toolgroup factory.
7791 * @return {OO.Factory} Toolgroup factory
7793 OO
.ui
.Toolbar
.prototype.getToolGroupFactory = function () {
7794 return this.toolGroupFactory
;
7798 * Handles mouse down events.
7801 * @param {jQuery.Event} e Mouse down event
7803 OO
.ui
.Toolbar
.prototype.onPointerDown = function ( e
) {
7804 var $closestWidgetToEvent
= $( e
.target
).closest( '.oo-ui-widget' ),
7805 $closestWidgetToToolbar
= this.$element
.closest( '.oo-ui-widget' );
7806 if ( !$closestWidgetToEvent
.length
|| $closestWidgetToEvent
[ 0 ] === $closestWidgetToToolbar
[ 0 ] ) {
7812 * Handle window resize event.
7815 * @param {jQuery.Event} e Window resize event
7817 OO
.ui
.Toolbar
.prototype.onWindowResize = function () {
7818 this.$element
.toggleClass(
7819 'oo-ui-toolbar-narrow',
7820 this.$bar
.width() <= this.narrowThreshold
7825 * Sets up handles and preloads required information for the toolbar to work.
7826 * This must be called after it is attached to a visible document and before doing anything else.
7828 OO
.ui
.Toolbar
.prototype.initialize = function () {
7829 if ( !this.initialized
) {
7830 this.initialized
= true;
7831 this.narrowThreshold
= this.$group
.width() + this.$actions
.width();
7832 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
7833 this.onWindowResize();
7838 * Set up the toolbar.
7840 * The toolbar is set up with a list of toolgroup configurations that specify the type of
7841 * toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or {@link OO.ui.ListToolGroup list})
7842 * to add and which tools to include, exclude, promote, or demote within that toolgroup. Please
7843 * see {@link OO.ui.ToolGroup toolgroups} for more information about including tools in toolgroups.
7845 * @param {Object.<string,Array>} groups List of toolgroup configurations
7846 * @param {Array|string} [groups.include] Tools to include in the toolgroup
7847 * @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup
7848 * @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup
7849 * @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup
7851 OO
.ui
.Toolbar
.prototype.setup = function ( groups
) {
7852 var i
, len
, type
, group
,
7854 defaultType
= 'bar';
7856 // Cleanup previous groups
7859 // Build out new groups
7860 for ( i
= 0, len
= groups
.length
; i
< len
; i
++ ) {
7861 group
= groups
[ i
];
7862 if ( group
.include
=== '*' ) {
7863 // Apply defaults to catch-all groups
7864 if ( group
.type
=== undefined ) {
7865 group
.type
= 'list';
7867 if ( group
.label
=== undefined ) {
7868 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
7871 // Check type has been registered
7872 type
= this.getToolGroupFactory().lookup( group
.type
) ? group
.type
: defaultType
;
7874 this.getToolGroupFactory().create( type
, this, group
)
7877 this.addItems( items
);
7881 * Remove all tools and toolgroups from the toolbar.
7883 OO
.ui
.Toolbar
.prototype.reset = function () {
7888 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
7889 this.items
[ i
].destroy();
7895 * Destroy the toolbar.
7897 * Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. Call
7898 * this method whenever you are done using a toolbar.
7900 OO
.ui
.Toolbar
.prototype.destroy = function () {
7901 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
7903 this.$element
.remove();
7907 * Check if the tool is available.
7909 * Available tools are ones that have not yet been added to the toolbar.
7911 * @param {string} name Symbolic name of tool
7912 * @return {boolean} Tool is available
7914 OO
.ui
.Toolbar
.prototype.isToolAvailable = function ( name
) {
7915 return !this.tools
[ name
];
7919 * Prevent tool from being used again.
7921 * @param {OO.ui.Tool} tool Tool to reserve
7923 OO
.ui
.Toolbar
.prototype.reserveTool = function ( tool
) {
7924 this.tools
[ tool
.getName() ] = tool
;
7928 * Allow tool to be used again.
7930 * @param {OO.ui.Tool} tool Tool to release
7932 OO
.ui
.Toolbar
.prototype.releaseTool = function ( tool
) {
7933 delete this.tools
[ tool
.getName() ];
7937 * Get accelerator label for tool.
7939 * The OOjs UI library does not contain an accelerator system, but this is the hook for one. To
7940 * use an accelerator system, subclass the toolbar and override this method, which is meant to return a label
7941 * that describes the accelerator keys for the tool passed (by symbolic name) to the method.
7943 * @param {string} name Symbolic name of tool
7944 * @return {string|undefined} Tool accelerator label if available
7946 OO
.ui
.Toolbar
.prototype.getToolAccelerator = function () {
7951 * ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a {@link OO.ui.Toolbar toolbar}.
7952 * The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or {@link OO.ui.MenuToolGroup menu})
7953 * to which a tool belongs determines how the tool is arranged and displayed in the toolbar. Toolgroups
7954 * themselves are created on demand with a {@link OO.ui.ToolGroupFactory toolgroup factory}.
7956 * Toolgroups can contain individual tools, groups of tools, or all available tools:
7958 * To include an individual tool (or array of individual tools), specify tools by symbolic name:
7960 * include: [ 'tool-name' ] or [ { name: 'tool-name' }]
7962 * 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.)
7964 * include: [ { group: 'group-name' } ]
7966 * To include all tools that are not yet assigned to a toolgroup, use the catch-all selector, an asterisk (*):
7970 * See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in general,
7971 * please see the [OOjs UI documentation on MediaWiki][1].
7973 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7977 * @extends OO.ui.Widget
7978 * @mixins OO.ui.mixin.GroupElement
7981 * @param {OO.ui.Toolbar} toolbar
7982 * @param {Object} [config] Configuration options
7983 * @cfg {Array|string} [include=[]] List of tools to include in the toolgroup.
7984 * @cfg {Array|string} [exclude=[]] List of tools to exclude from the toolgroup.
7985 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning of the toolgroup.
7986 * @cfg {Array|string} [demote=[]] List of tools to demote to the end of the toolgroup.
7987 * This setting is particularly useful when tools have been added to the toolgroup
7988 * en masse (e.g., via the catch-all selector).
7990 OO
.ui
.ToolGroup
= function OoUiToolGroup( toolbar
, config
) {
7991 // Allow passing positional parameters inside the config object
7992 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
7994 toolbar
= config
.toolbar
;
7997 // Configuration initialization
7998 config
= config
|| {};
8000 // Parent constructor
8001 OO
.ui
.ToolGroup
.parent
.call( this, config
);
8003 // Mixin constructors
8004 OO
.ui
.mixin
.GroupElement
.call( this, config
);
8007 this.toolbar
= toolbar
;
8009 this.pressed
= null;
8010 this.autoDisabled
= false;
8011 this.include
= config
.include
|| [];
8012 this.exclude
= config
.exclude
|| [];
8013 this.promote
= config
.promote
|| [];
8014 this.demote
= config
.demote
|| [];
8015 this.onCapturedMouseKeyUpHandler
= this.onCapturedMouseKeyUp
.bind( this );
8019 mousedown
: this.onMouseKeyDown
.bind( this ),
8020 mouseup
: this.onMouseKeyUp
.bind( this ),
8021 keydown
: this.onMouseKeyDown
.bind( this ),
8022 keyup
: this.onMouseKeyUp
.bind( this ),
8023 focus
: this.onMouseOverFocus
.bind( this ),
8024 blur
: this.onMouseOutBlur
.bind( this ),
8025 mouseover
: this.onMouseOverFocus
.bind( this ),
8026 mouseout
: this.onMouseOutBlur
.bind( this )
8028 this.toolbar
.getToolFactory().connect( this, { register
: 'onToolFactoryRegister' } );
8029 this.aggregate( { disable
: 'itemDisable' } );
8030 this.connect( this, { itemDisable
: 'updateDisabled' } );
8033 this.$group
.addClass( 'oo-ui-toolGroup-tools' );
8035 .addClass( 'oo-ui-toolGroup' )
8036 .append( this.$group
);
8042 OO
.inheritClass( OO
.ui
.ToolGroup
, OO
.ui
.Widget
);
8043 OO
.mixinClass( OO
.ui
.ToolGroup
, OO
.ui
.mixin
.GroupElement
);
8051 /* Static Properties */
8054 * Show labels in tooltips.
8058 * @property {boolean}
8060 OO
.ui
.ToolGroup
.static.titleTooltips
= false;
8063 * Show acceleration labels in tooltips.
8065 * Note: The OOjs UI library does not include an accelerator system, but does contain
8066 * a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and
8067 * override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is
8068 * meant to return a label that describes the accelerator keys for a given tool (e.g., 'Ctrl + M').
8072 * @property {boolean}
8074 OO
.ui
.ToolGroup
.static.accelTooltips
= false;
8077 * Automatically disable the toolgroup when all tools are disabled
8081 * @property {boolean}
8083 OO
.ui
.ToolGroup
.static.autoDisable
= true;
8090 OO
.ui
.ToolGroup
.prototype.isDisabled = function () {
8091 return this.autoDisabled
|| OO
.ui
.ToolGroup
.parent
.prototype.isDisabled
.apply( this, arguments
);
8097 OO
.ui
.ToolGroup
.prototype.updateDisabled = function () {
8098 var i
, item
, allDisabled
= true;
8100 if ( this.constructor.static.autoDisable
) {
8101 for ( i
= this.items
.length
- 1; i
>= 0; i
-- ) {
8102 item
= this.items
[ i
];
8103 if ( !item
.isDisabled() ) {
8104 allDisabled
= false;
8108 this.autoDisabled
= allDisabled
;
8110 OO
.ui
.ToolGroup
.parent
.prototype.updateDisabled
.apply( this, arguments
);
8114 * Handle mouse down and key down events.
8117 * @param {jQuery.Event} e Mouse down or key down event
8119 OO
.ui
.ToolGroup
.prototype.onMouseKeyDown = function ( e
) {
8121 !this.isDisabled() &&
8122 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
8124 this.pressed
= this.getTargetTool( e
);
8125 if ( this.pressed
) {
8126 this.pressed
.setActive( true );
8127 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler
);
8128 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler
);
8135 * Handle captured mouse up and key up events.
8138 * @param {Event} e Mouse up or key up event
8140 OO
.ui
.ToolGroup
.prototype.onCapturedMouseKeyUp = function ( e
) {
8141 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler
);
8142 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler
);
8143 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
8144 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
8145 this.onMouseKeyUp( e
);
8149 * Handle mouse up and key up events.
8152 * @param {jQuery.Event} e Mouse up or key up event
8154 OO
.ui
.ToolGroup
.prototype.onMouseKeyUp = function ( e
) {
8155 var tool
= this.getTargetTool( e
);
8158 !this.isDisabled() && this.pressed
&& this.pressed
=== tool
&&
8159 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
8161 this.pressed
.onSelect();
8162 this.pressed
= null;
8166 this.pressed
= null;
8170 * Handle mouse over and focus events.
8173 * @param {jQuery.Event} e Mouse over or focus event
8175 OO
.ui
.ToolGroup
.prototype.onMouseOverFocus = function ( e
) {
8176 var tool
= this.getTargetTool( e
);
8178 if ( this.pressed
&& this.pressed
=== tool
) {
8179 this.pressed
.setActive( true );
8184 * Handle mouse out and blur events.
8187 * @param {jQuery.Event} e Mouse out or blur event
8189 OO
.ui
.ToolGroup
.prototype.onMouseOutBlur = function ( e
) {
8190 var tool
= this.getTargetTool( e
);
8192 if ( this.pressed
&& this.pressed
=== tool
) {
8193 this.pressed
.setActive( false );
8198 * Get the closest tool to a jQuery.Event.
8200 * Only tool links are considered, which prevents other elements in the tool such as popups from
8201 * triggering tool group interactions.
8204 * @param {jQuery.Event} e
8205 * @return {OO.ui.Tool|null} Tool, `null` if none was found
8207 OO
.ui
.ToolGroup
.prototype.getTargetTool = function ( e
) {
8209 $item
= $( e
.target
).closest( '.oo-ui-tool-link' );
8211 if ( $item
.length
) {
8212 tool
= $item
.parent().data( 'oo-ui-tool' );
8215 return tool
&& !tool
.isDisabled() ? tool
: null;
8219 * Handle tool registry register events.
8221 * If a tool is registered after the group is created, we must repopulate the list to account for:
8223 * - a tool being added that may be included
8224 * - a tool already included being overridden
8227 * @param {string} name Symbolic name of tool
8229 OO
.ui
.ToolGroup
.prototype.onToolFactoryRegister = function () {
8234 * Get the toolbar that contains the toolgroup.
8236 * @return {OO.ui.Toolbar} Toolbar that contains the toolgroup
8238 OO
.ui
.ToolGroup
.prototype.getToolbar = function () {
8239 return this.toolbar
;
8243 * Add and remove tools based on configuration.
8245 OO
.ui
.ToolGroup
.prototype.populate = function () {
8246 var i
, len
, name
, tool
,
8247 toolFactory
= this.toolbar
.getToolFactory(),
8251 list
= this.toolbar
.getToolFactory().getTools(
8252 this.include
, this.exclude
, this.promote
, this.demote
8255 // Build a list of needed tools
8256 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
8260 toolFactory
.lookup( name
) &&
8261 // Tool is available or is already in this group
8262 ( this.toolbar
.isToolAvailable( name
) || this.tools
[ name
] )
8264 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
8265 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
8266 this.toolbar
.tools
[ name
] = true;
8267 tool
= this.tools
[ name
];
8269 // Auto-initialize tools on first use
8270 this.tools
[ name
] = tool
= toolFactory
.create( name
, this );
8273 this.toolbar
.reserveTool( tool
);
8275 names
[ name
] = true;
8278 // Remove tools that are no longer needed
8279 for ( name
in this.tools
) {
8280 if ( !names
[ name
] ) {
8281 this.tools
[ name
].destroy();
8282 this.toolbar
.releaseTool( this.tools
[ name
] );
8283 remove
.push( this.tools
[ name
] );
8284 delete this.tools
[ name
];
8287 if ( remove
.length
) {
8288 this.removeItems( remove
);
8290 // Update emptiness state
8292 this.$element
.removeClass( 'oo-ui-toolGroup-empty' );
8294 this.$element
.addClass( 'oo-ui-toolGroup-empty' );
8296 // Re-add tools (moving existing ones to new locations)
8297 this.addItems( add
);
8298 // Disabled state may depend on items
8299 this.updateDisabled();
8303 * Destroy toolgroup.
8305 OO
.ui
.ToolGroup
.prototype.destroy = function () {
8309 this.toolbar
.getToolFactory().disconnect( this );
8310 for ( name
in this.tools
) {
8311 this.toolbar
.releaseTool( this.tools
[ name
] );
8312 this.tools
[ name
].disconnect( this ).destroy();
8313 delete this.tools
[ name
];
8315 this.$element
.remove();
8319 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
8320 * consists of a header that contains the dialog title, a body with the message, and a footer that
8321 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
8322 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
8324 * There are two basic types of message dialogs, confirmation and alert:
8326 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
8327 * more details about the consequences.
8328 * - **alert**: the dialog title describes which event occurred and the message provides more information
8329 * about why the event occurred.
8331 * The MessageDialog class specifies two actions: ‘accept’, the primary
8332 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
8333 * passing along the selected action.
8335 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
8338 * // Example: Creating and opening a message dialog window.
8339 * var messageDialog = new OO.ui.MessageDialog();
8341 * // Create and append a window manager.
8342 * var windowManager = new OO.ui.WindowManager();
8343 * $( 'body' ).append( windowManager.$element );
8344 * windowManager.addWindows( [ messageDialog ] );
8345 * // Open the window.
8346 * windowManager.openWindow( messageDialog, {
8347 * title: 'Basic message dialog',
8348 * message: 'This is the message'
8351 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
8354 * @extends OO.ui.Dialog
8357 * @param {Object} [config] Configuration options
8359 OO
.ui
.MessageDialog
= function OoUiMessageDialog( config
) {
8360 // Parent constructor
8361 OO
.ui
.MessageDialog
.parent
.call( this, config
);
8364 this.verticalActionLayout
= null;
8367 this.$element
.addClass( 'oo-ui-messageDialog' );
8372 OO
.inheritClass( OO
.ui
.MessageDialog
, OO
.ui
.Dialog
);
8374 /* Static Properties */
8376 OO
.ui
.MessageDialog
.static.name
= 'message';
8378 OO
.ui
.MessageDialog
.static.size
= 'small';
8380 OO
.ui
.MessageDialog
.static.verbose
= false;
8385 * The title of a confirmation dialog describes what a progressive action will do. The
8386 * title of an alert dialog describes which event occurred.
8390 * @property {jQuery|string|Function|null}
8392 OO
.ui
.MessageDialog
.static.title
= null;
8395 * The message displayed in the dialog body.
8397 * A confirmation message describes the consequences of a progressive action. An alert
8398 * message describes why an event occurred.
8402 * @property {jQuery|string|Function|null}
8404 OO
.ui
.MessageDialog
.static.message
= null;
8406 OO
.ui
.MessageDialog
.static.actions
= [
8407 { action
: 'accept', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-accept' ), flags
: 'primary' },
8408 { action
: 'reject', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-reject' ), flags
: 'safe' }
8416 OO
.ui
.MessageDialog
.prototype.setManager = function ( manager
) {
8417 OO
.ui
.MessageDialog
.parent
.prototype.setManager
.call( this, manager
);
8420 this.manager
.connect( this, {
8430 OO
.ui
.MessageDialog
.prototype.onActionResize = function ( action
) {
8432 return OO
.ui
.MessageDialog
.parent
.prototype.onActionResize
.call( this, action
);
8436 * Handle window resized events.
8440 OO
.ui
.MessageDialog
.prototype.onResize = function () {
8442 dialog
.fitActions();
8443 // Wait for CSS transition to finish and do it again :(
8444 setTimeout( function () {
8445 dialog
.fitActions();
8450 * Toggle action layout between vertical and horizontal.
8453 * @param {boolean} [value] Layout actions vertically, omit to toggle
8456 OO
.ui
.MessageDialog
.prototype.toggleVerticalActionLayout = function ( value
) {
8457 value
= value
=== undefined ? !this.verticalActionLayout
: !!value
;
8459 if ( value
!== this.verticalActionLayout
) {
8460 this.verticalActionLayout
= value
;
8462 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value
)
8463 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value
);
8472 OO
.ui
.MessageDialog
.prototype.getActionProcess = function ( action
) {
8474 return new OO
.ui
.Process( function () {
8475 this.close( { action
: action
} );
8478 return OO
.ui
.MessageDialog
.parent
.prototype.getActionProcess
.call( this, action
);
8484 * @param {Object} [data] Dialog opening data
8485 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
8486 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
8487 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
8488 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
8491 OO
.ui
.MessageDialog
.prototype.getSetupProcess = function ( data
) {
8495 return OO
.ui
.MessageDialog
.parent
.prototype.getSetupProcess
.call( this, data
)
8496 .next( function () {
8497 this.title
.setLabel(
8498 data
.title
!== undefined ? data
.title
: this.constructor.static.title
8500 this.message
.setLabel(
8501 data
.message
!== undefined ? data
.message
: this.constructor.static.message
8503 this.message
.$element
.toggleClass(
8504 'oo-ui-messageDialog-message-verbose',
8505 data
.verbose
!== undefined ? data
.verbose
: this.constructor.static.verbose
8513 OO
.ui
.MessageDialog
.prototype.getReadyProcess = function ( data
) {
8517 return OO
.ui
.MessageDialog
.parent
.prototype.getReadyProcess
.call( this, data
)
8518 .next( function () {
8519 // Focus the primary action button
8520 var actions
= this.actions
.get();
8521 actions
= actions
.filter( function ( action
) {
8522 return action
.getFlags().indexOf( 'primary' ) > -1;
8524 if ( actions
.length
> 0 ) {
8525 actions
[ 0 ].$button
.focus();
8533 OO
.ui
.MessageDialog
.prototype.getBodyHeight = function () {
8534 var bodyHeight
, oldOverflow
,
8535 $scrollable
= this.container
.$element
;
8537 oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
8538 $scrollable
[ 0 ].style
.overflow
= 'hidden';
8540 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
8542 bodyHeight
= this.text
.$element
.outerHeight( true );
8543 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
8551 OO
.ui
.MessageDialog
.prototype.setDimensions = function ( dim
) {
8552 var $scrollable
= this.container
.$element
;
8553 OO
.ui
.MessageDialog
.parent
.prototype.setDimensions
.call( this, dim
);
8555 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
8556 // Need to do it after transition completes (250ms), add 50ms just in case.
8557 setTimeout( function () {
8558 var oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
8559 $scrollable
[ 0 ].style
.overflow
= 'hidden';
8561 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
8563 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
8572 OO
.ui
.MessageDialog
.prototype.initialize = function () {
8574 OO
.ui
.MessageDialog
.parent
.prototype.initialize
.call( this );
8577 this.$actions
= $( '<div>' );
8578 this.container
= new OO
.ui
.PanelLayout( {
8579 scrollable
: true, classes
: [ 'oo-ui-messageDialog-container' ]
8581 this.text
= new OO
.ui
.PanelLayout( {
8582 padded
: true, expanded
: false, classes
: [ 'oo-ui-messageDialog-text' ]
8584 this.message
= new OO
.ui
.LabelWidget( {
8585 classes
: [ 'oo-ui-messageDialog-message' ]
8589 this.title
.$element
.addClass( 'oo-ui-messageDialog-title' );
8590 this.$content
.addClass( 'oo-ui-messageDialog-content' );
8591 this.container
.$element
.append( this.text
.$element
);
8592 this.text
.$element
.append( this.title
.$element
, this.message
.$element
);
8593 this.$body
.append( this.container
.$element
);
8594 this.$actions
.addClass( 'oo-ui-messageDialog-actions' );
8595 this.$foot
.append( this.$actions
);
8601 OO
.ui
.MessageDialog
.prototype.attachActions = function () {
8602 var i
, len
, other
, special
, others
;
8605 OO
.ui
.MessageDialog
.parent
.prototype.attachActions
.call( this );
8607 special
= this.actions
.getSpecial();
8608 others
= this.actions
.getOthers();
8610 if ( special
.safe
) {
8611 this.$actions
.append( special
.safe
.$element
);
8612 special
.safe
.toggleFramed( false );
8614 if ( others
.length
) {
8615 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
8616 other
= others
[ i
];
8617 this.$actions
.append( other
.$element
);
8618 other
.toggleFramed( false );
8621 if ( special
.primary
) {
8622 this.$actions
.append( special
.primary
.$element
);
8623 special
.primary
.toggleFramed( false );
8626 if ( !this.isOpening() ) {
8627 // If the dialog is currently opening, this will be called automatically soon.
8628 // This also calls #fitActions.
8634 * Fit action actions into columns or rows.
8636 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
8640 OO
.ui
.MessageDialog
.prototype.fitActions = function () {
8642 previous
= this.verticalActionLayout
,
8643 actions
= this.actions
.get();
8646 this.toggleVerticalActionLayout( false );
8647 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
8648 action
= actions
[ i
];
8649 if ( action
.$element
.innerWidth() < action
.$label
.outerWidth( true ) ) {
8650 this.toggleVerticalActionLayout( true );
8655 // Move the body out of the way of the foot
8656 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
8658 if ( this.verticalActionLayout
!== previous
) {
8659 // We changed the layout, window height might need to be updated.
8665 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
8666 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
8667 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
8668 * relevant. The ProcessDialog class is always extended and customized with the actions and content
8669 * required for each process.
8671 * The process dialog box consists of a header that visually represents the ‘working’ state of long
8672 * processes with an animation. The header contains the dialog title as well as
8673 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
8674 * a ‘primary’ action on the right (e.g., ‘Done’).
8676 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
8677 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
8680 * // Example: Creating and opening a process dialog window.
8681 * function MyProcessDialog( config ) {
8682 * MyProcessDialog.parent.call( this, config );
8684 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
8686 * MyProcessDialog.static.title = 'Process dialog';
8687 * MyProcessDialog.static.actions = [
8688 * { action: 'save', label: 'Done', flags: 'primary' },
8689 * { label: 'Cancel', flags: 'safe' }
8692 * MyProcessDialog.prototype.initialize = function () {
8693 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
8694 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
8695 * 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>' );
8696 * this.$body.append( this.content.$element );
8698 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
8699 * var dialog = this;
8701 * return new OO.ui.Process( function () {
8702 * dialog.close( { action: action } );
8705 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
8708 * var windowManager = new OO.ui.WindowManager();
8709 * $( 'body' ).append( windowManager.$element );
8711 * var dialog = new MyProcessDialog();
8712 * windowManager.addWindows( [ dialog ] );
8713 * windowManager.openWindow( dialog );
8715 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
8719 * @extends OO.ui.Dialog
8722 * @param {Object} [config] Configuration options
8724 OO
.ui
.ProcessDialog
= function OoUiProcessDialog( config
) {
8725 // Parent constructor
8726 OO
.ui
.ProcessDialog
.parent
.call( this, config
);
8729 this.fitOnOpen
= false;
8732 this.$element
.addClass( 'oo-ui-processDialog' );
8737 OO
.inheritClass( OO
.ui
.ProcessDialog
, OO
.ui
.Dialog
);
8742 * Handle dismiss button click events.
8748 OO
.ui
.ProcessDialog
.prototype.onDismissErrorButtonClick = function () {
8753 * Handle retry button click events.
8755 * Hides errors and then tries again.
8759 OO
.ui
.ProcessDialog
.prototype.onRetryButtonClick = function () {
8761 this.executeAction( this.currentAction
);
8767 OO
.ui
.ProcessDialog
.prototype.onActionResize = function ( action
) {
8768 if ( this.actions
.isSpecial( action
) ) {
8771 return OO
.ui
.ProcessDialog
.parent
.prototype.onActionResize
.call( this, action
);
8777 OO
.ui
.ProcessDialog
.prototype.initialize = function () {
8779 OO
.ui
.ProcessDialog
.parent
.prototype.initialize
.call( this );
8782 this.$navigation
= $( '<div>' );
8783 this.$location
= $( '<div>' );
8784 this.$safeActions
= $( '<div>' );
8785 this.$primaryActions
= $( '<div>' );
8786 this.$otherActions
= $( '<div>' );
8787 this.dismissButton
= new OO
.ui
.ButtonWidget( {
8788 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' )
8790 this.retryButton
= new OO
.ui
.ButtonWidget();
8791 this.$errors
= $( '<div>' );
8792 this.$errorsTitle
= $( '<div>' );
8795 this.dismissButton
.connect( this, { click
: 'onDismissErrorButtonClick' } );
8796 this.retryButton
.connect( this, { click
: 'onRetryButtonClick' } );
8799 this.title
.$element
.addClass( 'oo-ui-processDialog-title' );
8801 .append( this.title
.$element
)
8802 .addClass( 'oo-ui-processDialog-location' );
8803 this.$safeActions
.addClass( 'oo-ui-processDialog-actions-safe' );
8804 this.$primaryActions
.addClass( 'oo-ui-processDialog-actions-primary' );
8805 this.$otherActions
.addClass( 'oo-ui-processDialog-actions-other' );
8807 .addClass( 'oo-ui-processDialog-errors-title' )
8808 .text( OO
.ui
.msg( 'ooui-dialog-process-error' ) );
8810 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
8811 .append( this.$errorsTitle
, this.dismissButton
.$element
, this.retryButton
.$element
);
8813 .addClass( 'oo-ui-processDialog-content' )
8814 .append( this.$errors
);
8816 .addClass( 'oo-ui-processDialog-navigation' )
8817 .append( this.$safeActions
, this.$location
, this.$primaryActions
);
8818 this.$head
.append( this.$navigation
);
8819 this.$foot
.append( this.$otherActions
);
8825 OO
.ui
.ProcessDialog
.prototype.getActionWidgets = function ( actions
) {
8826 var i
, len
, widgets
= [];
8827 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
8829 new OO
.ui
.ActionWidget( $.extend( { framed
: true }, actions
[ i
] ) )
8838 OO
.ui
.ProcessDialog
.prototype.attachActions = function () {
8839 var i
, len
, other
, special
, others
;
8842 OO
.ui
.ProcessDialog
.parent
.prototype.attachActions
.call( this );
8844 special
= this.actions
.getSpecial();
8845 others
= this.actions
.getOthers();
8846 if ( special
.primary
) {
8847 this.$primaryActions
.append( special
.primary
.$element
);
8849 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
8850 other
= others
[ i
];
8851 this.$otherActions
.append( other
.$element
);
8853 if ( special
.safe
) {
8854 this.$safeActions
.append( special
.safe
.$element
);
8858 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
8864 OO
.ui
.ProcessDialog
.prototype.executeAction = function ( action
) {
8866 return OO
.ui
.ProcessDialog
.parent
.prototype.executeAction
.call( this, action
)
8867 .fail( function ( errors
) {
8868 process
.showErrors( errors
|| [] );
8875 OO
.ui
.ProcessDialog
.prototype.setDimensions = function () {
8877 OO
.ui
.ProcessDialog
.parent
.prototype.setDimensions
.apply( this, arguments
);
8883 * Fit label between actions.
8888 OO
.ui
.ProcessDialog
.prototype.fitLabel = function () {
8889 var safeWidth
, primaryWidth
, biggerWidth
, labelWidth
, navigationWidth
, leftWidth
, rightWidth
,
8890 size
= this.getSizeProperties();
8892 if ( typeof size
.width
!== 'number' ) {
8893 if ( this.isOpened() ) {
8894 navigationWidth
= this.$head
.width() - 20;
8895 } else if ( this.isOpening() ) {
8896 if ( !this.fitOnOpen
) {
8897 // Size is relative and the dialog isn't open yet, so wait.
8898 this.manager
.opening
.done( this.fitLabel
.bind( this ) );
8899 this.fitOnOpen
= true;
8906 navigationWidth
= size
.width
- 20;
8909 safeWidth
= this.$safeActions
.is( ':visible' ) ? this.$safeActions
.width() : 0;
8910 primaryWidth
= this.$primaryActions
.is( ':visible' ) ? this.$primaryActions
.width() : 0;
8911 biggerWidth
= Math
.max( safeWidth
, primaryWidth
);
8913 labelWidth
= this.title
.$element
.width();
8915 if ( 2 * biggerWidth
+ labelWidth
< navigationWidth
) {
8916 // We have enough space to center the label
8917 leftWidth
= rightWidth
= biggerWidth
;
8919 // Let's hope we at least have enough space not to overlap, because we can't wrap the label…
8920 if ( this.getDir() === 'ltr' ) {
8921 leftWidth
= safeWidth
;
8922 rightWidth
= primaryWidth
;
8924 leftWidth
= primaryWidth
;
8925 rightWidth
= safeWidth
;
8929 this.$location
.css( { paddingLeft
: leftWidth
, paddingRight
: rightWidth
} );
8935 * Handle errors that occurred during accept or reject processes.
8938 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
8940 OO
.ui
.ProcessDialog
.prototype.showErrors = function ( errors
) {
8941 var i
, len
, $item
, actions
,
8947 if ( errors
instanceof OO
.ui
.Error
) {
8948 errors
= [ errors
];
8951 for ( i
= 0, len
= errors
.length
; i
< len
; i
++ ) {
8952 if ( !errors
[ i
].isRecoverable() ) {
8953 recoverable
= false;
8955 if ( errors
[ i
].isWarning() ) {
8958 $item
= $( '<div>' )
8959 .addClass( 'oo-ui-processDialog-error' )
8960 .append( errors
[ i
].getMessage() );
8961 items
.push( $item
[ 0 ] );
8963 this.$errorItems
= $( items
);
8964 if ( recoverable
) {
8965 abilities
[ this.currentAction
] = true;
8966 // Copy the flags from the first matching action
8967 actions
= this.actions
.get( { actions
: this.currentAction
} );
8968 if ( actions
.length
) {
8969 this.retryButton
.clearFlags().setFlags( actions
[ 0 ].getFlags() );
8972 abilities
[ this.currentAction
] = false;
8973 this.actions
.setAbilities( abilities
);
8976 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-continue' ) );
8978 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-retry' ) );
8980 this.retryButton
.toggle( recoverable
);
8981 this.$errorsTitle
.after( this.$errorItems
);
8982 this.$errors
.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
8990 OO
.ui
.ProcessDialog
.prototype.hideErrors = function () {
8991 this.$errors
.addClass( 'oo-ui-element-hidden' );
8992 if ( this.$errorItems
) {
8993 this.$errorItems
.remove();
8994 this.$errorItems
= null;
9001 OO
.ui
.ProcessDialog
.prototype.getTeardownProcess = function ( data
) {
9003 return OO
.ui
.ProcessDialog
.parent
.prototype.getTeardownProcess
.call( this, data
)
9004 .first( function () {
9005 // Make sure to hide errors
9007 this.fitOnOpen
= false;
9012 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
9013 * which is a widget that is specified by reference before any optional configuration settings.
9015 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
9017 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9018 * A left-alignment is used for forms with many fields.
9019 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9020 * A right-alignment is used for long but familiar forms which users tab through,
9021 * verifying the current field with a quick glance at the label.
9022 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9023 * that users fill out from top to bottom.
9024 * - **inline**: The label is placed after the field-widget and aligned to the left.
9025 * An inline-alignment is best used with checkboxes or radio buttons.
9027 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
9028 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
9030 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9032 * @extends OO.ui.Layout
9033 * @mixins OO.ui.mixin.LabelElement
9034 * @mixins OO.ui.mixin.TitledElement
9037 * @param {OO.ui.Widget} fieldWidget Field widget
9038 * @param {Object} [config] Configuration options
9039 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
9040 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
9041 * The array may contain strings or OO.ui.HtmlSnippet instances.
9042 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
9043 * The array may contain strings or OO.ui.HtmlSnippet instances.
9044 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
9045 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
9046 * For important messages, you are advised to use `notices`, as they are always shown.
9048 * @throws {Error} An error is thrown if no widget is specified
9050 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
9051 var hasInputWidget
, div
;
9053 // Allow passing positional parameters inside the config object
9054 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
9055 config
= fieldWidget
;
9056 fieldWidget
= config
.fieldWidget
;
9059 // Make sure we have required constructor arguments
9060 if ( fieldWidget
=== undefined ) {
9061 throw new Error( 'Widget not found' );
9064 hasInputWidget
= fieldWidget
.constructor.static.supportsSimpleLabel
;
9066 // Configuration initialization
9067 config
= $.extend( { align
: 'left' }, config
);
9069 // Parent constructor
9070 OO
.ui
.FieldLayout
.parent
.call( this, config
);
9072 // Mixin constructors
9073 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9074 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
9077 this.fieldWidget
= fieldWidget
;
9080 this.$field
= $( '<div>' );
9081 this.$messages
= $( '<ul>' );
9082 this.$body
= $( '<' + ( hasInputWidget
? 'label' : 'div' ) + '>' );
9084 if ( config
.help
) {
9085 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
9086 classes
: [ 'oo-ui-fieldLayout-help' ],
9092 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
9093 div
.html( config
.help
.toString() );
9095 div
.text( config
.help
);
9097 this.popupButtonWidget
.getPopup().$body
.append(
9098 div
.addClass( 'oo-ui-fieldLayout-help-content' )
9100 this.$help
= this.popupButtonWidget
.$element
;
9102 this.$help
= $( [] );
9106 if ( hasInputWidget
) {
9107 this.$label
.on( 'click', this.onLabelClick
.bind( this ) );
9109 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
9113 .addClass( 'oo-ui-fieldLayout' )
9114 .append( this.$help
, this.$body
);
9115 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
9116 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
9118 .addClass( 'oo-ui-fieldLayout-field' )
9119 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget
.isDisabled() )
9120 .append( this.fieldWidget
.$element
);
9122 this.setErrors( config
.errors
|| [] );
9123 this.setNotices( config
.notices
|| [] );
9124 this.setAlignment( config
.align
);
9129 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
9130 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
9131 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
9136 * Handle field disable events.
9139 * @param {boolean} value Field is disabled
9141 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
9142 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
9146 * Handle label mouse click events.
9149 * @param {jQuery.Event} e Mouse click event
9151 OO
.ui
.FieldLayout
.prototype.onLabelClick = function () {
9152 this.fieldWidget
.simulateLabelClick();
9157 * Get the widget contained by the field.
9159 * @return {OO.ui.Widget} Field widget
9161 OO
.ui
.FieldLayout
.prototype.getField = function () {
9162 return this.fieldWidget
;
9167 * @param {string} kind 'error' or 'notice'
9168 * @param {string|OO.ui.HtmlSnippet} text
9171 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
9172 var $listItem
, $icon
, message
;
9173 $listItem
= $( '<li>' );
9174 if ( kind
=== 'error' ) {
9175 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
9176 } else if ( kind
=== 'notice' ) {
9177 $icon
= new OO
.ui
.IconWidget( { icon
: 'info' } ).$element
;
9181 message
= new OO
.ui
.LabelWidget( { label
: text
} );
9183 .append( $icon
, message
.$element
)
9184 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
9189 * Set the field alignment mode.
9192 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
9195 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
9196 if ( value
!== this.align
) {
9197 // Default to 'left'
9198 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
9202 if ( value
=== 'inline' ) {
9203 this.$body
.append( this.$field
, this.$label
);
9205 this.$body
.append( this.$label
, this.$field
);
9207 // Set classes. The following classes can be used here:
9208 // * oo-ui-fieldLayout-align-left
9209 // * oo-ui-fieldLayout-align-right
9210 // * oo-ui-fieldLayout-align-top
9211 // * oo-ui-fieldLayout-align-inline
9213 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
9215 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
9223 * Set the list of error messages.
9225 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
9226 * The array may contain strings or OO.ui.HtmlSnippet instances.
9229 OO
.ui
.FieldLayout
.prototype.setErrors = function ( errors
) {
9230 this.errors
= errors
.slice();
9231 this.updateMessages();
9236 * Set the list of notice messages.
9238 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
9239 * The array may contain strings or OO.ui.HtmlSnippet instances.
9242 OO
.ui
.FieldLayout
.prototype.setNotices = function ( notices
) {
9243 this.notices
= notices
.slice();
9244 this.updateMessages();
9249 * Update the rendering of error and notice messages.
9253 OO
.ui
.FieldLayout
.prototype.updateMessages = function () {
9255 this.$messages
.empty();
9257 if ( this.errors
.length
|| this.notices
.length
) {
9258 this.$body
.after( this.$messages
);
9260 this.$messages
.remove();
9264 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
9265 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
9267 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
9268 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
9273 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
9274 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
9275 * is required and is specified before any optional configuration settings.
9277 * Labels can be aligned in one of four ways:
9279 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9280 * A left-alignment is used for forms with many fields.
9281 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9282 * A right-alignment is used for long but familiar forms which users tab through,
9283 * verifying the current field with a quick glance at the label.
9284 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9285 * that users fill out from top to bottom.
9286 * - **inline**: The label is placed after the field-widget and aligned to the left.
9287 * An inline-alignment is best used with checkboxes or radio buttons.
9289 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
9290 * text is specified.
9293 * // Example of an ActionFieldLayout
9294 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
9295 * new OO.ui.TextInputWidget( {
9296 * placeholder: 'Field widget'
9298 * new OO.ui.ButtonWidget( {
9302 * label: 'An ActionFieldLayout. This label is aligned top',
9304 * help: 'This is help text'
9308 * $( 'body' ).append( actionFieldLayout.$element );
9311 * @extends OO.ui.FieldLayout
9314 * @param {OO.ui.Widget} fieldWidget Field widget
9315 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
9317 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
9318 // Allow passing positional parameters inside the config object
9319 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
9320 config
= fieldWidget
;
9321 fieldWidget
= config
.fieldWidget
;
9322 buttonWidget
= config
.buttonWidget
;
9325 // Parent constructor
9326 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
9329 this.buttonWidget
= buttonWidget
;
9330 this.$button
= $( '<div>' );
9331 this.$input
= $( '<div>' );
9335 .addClass( 'oo-ui-actionFieldLayout' );
9337 .addClass( 'oo-ui-actionFieldLayout-button' )
9338 .append( this.buttonWidget
.$element
);
9340 .addClass( 'oo-ui-actionFieldLayout-input' )
9341 .append( this.fieldWidget
.$element
);
9343 .append( this.$input
, this.$button
);
9348 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
9351 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
9352 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
9353 * configured with a label as well. For more information and examples,
9354 * please see the [OOjs UI documentation on MediaWiki][1].
9357 * // Example of a fieldset layout
9358 * var input1 = new OO.ui.TextInputWidget( {
9359 * placeholder: 'A text input field'
9362 * var input2 = new OO.ui.TextInputWidget( {
9363 * placeholder: 'A text input field'
9366 * var fieldset = new OO.ui.FieldsetLayout( {
9367 * label: 'Example of a fieldset layout'
9370 * fieldset.addItems( [
9371 * new OO.ui.FieldLayout( input1, {
9372 * label: 'Field One'
9374 * new OO.ui.FieldLayout( input2, {
9375 * label: 'Field Two'
9378 * $( 'body' ).append( fieldset.$element );
9380 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9383 * @extends OO.ui.Layout
9384 * @mixins OO.ui.mixin.IconElement
9385 * @mixins OO.ui.mixin.LabelElement
9386 * @mixins OO.ui.mixin.GroupElement
9389 * @param {Object} [config] Configuration options
9390 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
9392 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
9393 // Configuration initialization
9394 config
= config
|| {};
9396 // Parent constructor
9397 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
9399 // Mixin constructors
9400 OO
.ui
.mixin
.IconElement
.call( this, config
);
9401 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9402 OO
.ui
.mixin
.GroupElement
.call( this, config
);
9404 if ( config
.help
) {
9405 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
9406 classes
: [ 'oo-ui-fieldsetLayout-help' ],
9411 this.popupButtonWidget
.getPopup().$body
.append(
9413 .text( config
.help
)
9414 .addClass( 'oo-ui-fieldsetLayout-help-content' )
9416 this.$help
= this.popupButtonWidget
.$element
;
9418 this.$help
= $( [] );
9423 .addClass( 'oo-ui-fieldsetLayout' )
9424 .prepend( this.$help
, this.$icon
, this.$label
, this.$group
);
9425 if ( Array
.isArray( config
.items
) ) {
9426 this.addItems( config
.items
);
9432 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
9433 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
9434 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
9435 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
9438 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
9439 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
9440 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
9441 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9443 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
9444 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
9445 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
9446 * some fancier controls. Some controls have both regular and InputWidget variants, for example
9447 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
9448 * often have simplified APIs to match the capabilities of HTML forms.
9449 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
9451 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
9452 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9455 * // Example of a form layout that wraps a fieldset layout
9456 * var input1 = new OO.ui.TextInputWidget( {
9457 * placeholder: 'Username'
9459 * var input2 = new OO.ui.TextInputWidget( {
9460 * placeholder: 'Password',
9463 * var submit = new OO.ui.ButtonInputWidget( {
9467 * var fieldset = new OO.ui.FieldsetLayout( {
9468 * label: 'A form layout'
9470 * fieldset.addItems( [
9471 * new OO.ui.FieldLayout( input1, {
9472 * label: 'Username',
9475 * new OO.ui.FieldLayout( input2, {
9476 * label: 'Password',
9479 * new OO.ui.FieldLayout( submit )
9481 * var form = new OO.ui.FormLayout( {
9482 * items: [ fieldset ],
9483 * action: '/api/formhandler',
9486 * $( 'body' ).append( form.$element );
9489 * @extends OO.ui.Layout
9490 * @mixins OO.ui.mixin.GroupElement
9493 * @param {Object} [config] Configuration options
9494 * @cfg {string} [method] HTML form `method` attribute
9495 * @cfg {string} [action] HTML form `action` attribute
9496 * @cfg {string} [enctype] HTML form `enctype` attribute
9497 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
9499 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
9500 // Configuration initialization
9501 config
= config
|| {};
9503 // Parent constructor
9504 OO
.ui
.FormLayout
.parent
.call( this, config
);
9506 // Mixin constructors
9507 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
9510 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
9512 // Make sure the action is safe
9513 if ( config
.action
!== undefined && !OO
.ui
.isSafeUrl( config
.action
) ) {
9514 throw new Error( 'Potentially unsafe action provided: ' + config
.action
);
9519 .addClass( 'oo-ui-formLayout' )
9521 method
: config
.method
,
9522 action
: config
.action
,
9523 enctype
: config
.enctype
9525 if ( Array
.isArray( config
.items
) ) {
9526 this.addItems( config
.items
);
9532 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
9533 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
9538 * A 'submit' event is emitted when the form is submitted.
9543 /* Static Properties */
9545 OO
.ui
.FormLayout
.static.tagName
= 'form';
9550 * Handle form submit events.
9553 * @param {jQuery.Event} e Submit event
9556 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
9557 if ( this.emit( 'submit' ) ) {
9563 * 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)
9564 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
9567 * var menuLayout = new OO.ui.MenuLayout( {
9570 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9571 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9572 * select = new OO.ui.SelectWidget( {
9574 * new OO.ui.OptionWidget( {
9578 * new OO.ui.OptionWidget( {
9582 * new OO.ui.OptionWidget( {
9586 * new OO.ui.OptionWidget( {
9591 * } ).on( 'select', function ( item ) {
9592 * menuLayout.setMenuPosition( item.getData() );
9595 * menuLayout.$menu.append(
9596 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
9598 * menuLayout.$content.append(
9599 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
9601 * $( 'body' ).append( menuLayout.$element );
9603 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
9604 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
9605 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
9608 * .oo-ui-menuLayout-menu {
9612 * .oo-ui-menuLayout-content {
9620 * @extends OO.ui.Layout
9623 * @param {Object} [config] Configuration options
9624 * @cfg {boolean} [showMenu=true] Show menu
9625 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
9627 OO
.ui
.MenuLayout
= function OoUiMenuLayout( config
) {
9628 // Configuration initialization
9629 config
= $.extend( {
9631 menuPosition
: 'before'
9634 // Parent constructor
9635 OO
.ui
.MenuLayout
.parent
.call( this, config
);
9640 * @property {jQuery}
9642 this.$menu
= $( '<div>' );
9646 * @property {jQuery}
9648 this.$content
= $( '<div>' );
9652 .addClass( 'oo-ui-menuLayout-menu' );
9653 this.$content
.addClass( 'oo-ui-menuLayout-content' );
9655 .addClass( 'oo-ui-menuLayout' )
9656 .append( this.$content
, this.$menu
);
9657 this.setMenuPosition( config
.menuPosition
);
9658 this.toggleMenu( config
.showMenu
);
9663 OO
.inheritClass( OO
.ui
.MenuLayout
, OO
.ui
.Layout
);
9670 * @param {boolean} showMenu Show menu, omit to toggle
9673 OO
.ui
.MenuLayout
.prototype.toggleMenu = function ( showMenu
) {
9674 showMenu
= showMenu
=== undefined ? !this.showMenu
: !!showMenu
;
9676 if ( this.showMenu
!== showMenu
) {
9677 this.showMenu
= showMenu
;
9679 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu
)
9680 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu
);
9687 * Check if menu is visible
9689 * @return {boolean} Menu is visible
9691 OO
.ui
.MenuLayout
.prototype.isMenuVisible = function () {
9692 return this.showMenu
;
9696 * Set menu position.
9698 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
9699 * @throws {Error} If position value is not supported
9702 OO
.ui
.MenuLayout
.prototype.setMenuPosition = function ( position
) {
9703 this.$element
.removeClass( 'oo-ui-menuLayout-' + this.menuPosition
);
9704 this.menuPosition
= position
;
9705 this.$element
.addClass( 'oo-ui-menuLayout-' + position
);
9711 * Get menu position.
9713 * @return {string} Menu position
9715 OO
.ui
.MenuLayout
.prototype.getMenuPosition = function () {
9716 return this.menuPosition
;
9720 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
9721 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
9722 * through the pages and select which one to display. By default, only one page is
9723 * displayed at a time and the outline is hidden. When a user navigates to a new page,
9724 * the booklet layout automatically focuses on the first focusable element, unless the
9725 * default setting is changed. Optionally, booklets can be configured to show
9726 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
9729 * // Example of a BookletLayout that contains two PageLayouts.
9731 * function PageOneLayout( name, config ) {
9732 * PageOneLayout.parent.call( this, name, config );
9733 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
9735 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
9736 * PageOneLayout.prototype.setupOutlineItem = function () {
9737 * this.outlineItem.setLabel( 'Page One' );
9740 * function PageTwoLayout( name, config ) {
9741 * PageTwoLayout.parent.call( this, name, config );
9742 * this.$element.append( '<p>Second page</p>' );
9744 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
9745 * PageTwoLayout.prototype.setupOutlineItem = function () {
9746 * this.outlineItem.setLabel( 'Page Two' );
9749 * var page1 = new PageOneLayout( 'one' ),
9750 * page2 = new PageTwoLayout( 'two' );
9752 * var booklet = new OO.ui.BookletLayout( {
9756 * booklet.addPages ( [ page1, page2 ] );
9757 * $( 'body' ).append( booklet.$element );
9760 * @extends OO.ui.MenuLayout
9763 * @param {Object} [config] Configuration options
9764 * @cfg {boolean} [continuous=false] Show all pages, one after another
9765 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
9766 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
9767 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
9769 OO
.ui
.BookletLayout
= function OoUiBookletLayout( config
) {
9770 // Configuration initialization
9771 config
= config
|| {};
9773 // Parent constructor
9774 OO
.ui
.BookletLayout
.parent
.call( this, config
);
9777 this.currentPageName
= null;
9779 this.ignoreFocus
= false;
9780 this.stackLayout
= new OO
.ui
.StackLayout( { continuous
: !!config
.continuous
} );
9781 this.$content
.append( this.stackLayout
.$element
);
9782 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
9783 this.outlineVisible
= false;
9784 this.outlined
= !!config
.outlined
;
9785 if ( this.outlined
) {
9786 this.editable
= !!config
.editable
;
9787 this.outlineControlsWidget
= null;
9788 this.outlineSelectWidget
= new OO
.ui
.OutlineSelectWidget();
9789 this.outlinePanel
= new OO
.ui
.PanelLayout( { scrollable
: true } );
9790 this.$menu
.append( this.outlinePanel
.$element
);
9791 this.outlineVisible
= true;
9792 if ( this.editable
) {
9793 this.outlineControlsWidget
= new OO
.ui
.OutlineControlsWidget(
9794 this.outlineSelectWidget
9798 this.toggleMenu( this.outlined
);
9801 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
9802 if ( this.outlined
) {
9803 this.outlineSelectWidget
.connect( this, { select
: 'onOutlineSelectWidgetSelect' } );
9804 this.scrolling
= false;
9805 this.stackLayout
.connect( this, { visibleItemChange
: 'onStackLayoutVisibleItemChange' } );
9807 if ( this.autoFocus
) {
9808 // Event 'focus' does not bubble, but 'focusin' does
9809 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
9813 this.$element
.addClass( 'oo-ui-bookletLayout' );
9814 this.stackLayout
.$element
.addClass( 'oo-ui-bookletLayout-stackLayout' );
9815 if ( this.outlined
) {
9816 this.outlinePanel
.$element
9817 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
9818 .append( this.outlineSelectWidget
.$element
);
9819 if ( this.editable
) {
9820 this.outlinePanel
.$element
9821 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
9822 .append( this.outlineControlsWidget
.$element
);
9829 OO
.inheritClass( OO
.ui
.BookletLayout
, OO
.ui
.MenuLayout
);
9834 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
9836 * @param {OO.ui.PageLayout} page Current page
9840 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
9843 * @param {OO.ui.PageLayout[]} page Added pages
9844 * @param {number} index Index pages were added at
9848 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
9849 * {@link #removePages removed} from the booklet.
9852 * @param {OO.ui.PageLayout[]} pages Removed pages
9858 * Handle stack layout focus.
9861 * @param {jQuery.Event} e Focusin event
9863 OO
.ui
.BookletLayout
.prototype.onStackLayoutFocus = function ( e
) {
9866 // Find the page that an element was focused within
9867 $target
= $( e
.target
).closest( '.oo-ui-pageLayout' );
9868 for ( name
in this.pages
) {
9869 // Check for page match, exclude current page to find only page changes
9870 if ( this.pages
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentPageName
) {
9871 this.setPage( name
);
9878 * Handle visibleItemChange events from the stackLayout
9880 * The next visible page is set as the current page by selecting it
9883 * @param {OO.ui.PageLayout} page The next visible page in the layout
9885 OO
.ui
.BookletLayout
.prototype.onStackLayoutVisibleItemChange = function ( page
) {
9886 // Set a flag to so that the resulting call to #onStackLayoutSet doesn't
9887 // try and scroll the item into view again.
9888 this.scrolling
= true;
9889 this.outlineSelectWidget
.selectItemByData( page
.getName() );
9890 this.scrolling
= false;
9894 * Handle stack layout set events.
9897 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
9899 OO
.ui
.BookletLayout
.prototype.onStackLayoutSet = function ( page
) {
9901 if ( !this.scrolling
&& page
) {
9902 page
.scrollElementIntoView( { complete: function () {
9903 if ( layout
.autoFocus
) {
9911 * Focus the first input in the current page.
9913 * If no page is selected, the first selectable page will be selected.
9914 * If the focus is already in an element on the current page, nothing will happen.
9915 * @param {number} [itemIndex] A specific item to focus on
9917 OO
.ui
.BookletLayout
.prototype.focus = function ( itemIndex
) {
9919 items
= this.stackLayout
.getItems();
9921 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
9922 page
= items
[ itemIndex
];
9924 page
= this.stackLayout
.getCurrentItem();
9927 if ( !page
&& this.outlined
) {
9928 this.selectFirstSelectablePage();
9929 page
= this.stackLayout
.getCurrentItem();
9934 // Only change the focus if is not already in the current page
9935 if ( !OO
.ui
.contains( page
.$element
[ 0 ], this.getElementDocument().activeElement
, true ) ) {
9941 * Find the first focusable input in the booklet layout and focus
9944 OO
.ui
.BookletLayout
.prototype.focusFirstFocusable = function () {
9945 OO
.ui
.findFocusable( this.stackLayout
.$element
).focus();
9949 * Handle outline widget select events.
9952 * @param {OO.ui.OptionWidget|null} item Selected item
9954 OO
.ui
.BookletLayout
.prototype.onOutlineSelectWidgetSelect = function ( item
) {
9956 this.setPage( item
.getData() );
9961 * Check if booklet has an outline.
9963 * @return {boolean} Booklet has an outline
9965 OO
.ui
.BookletLayout
.prototype.isOutlined = function () {
9966 return this.outlined
;
9970 * Check if booklet has editing controls.
9972 * @return {boolean} Booklet is editable
9974 OO
.ui
.BookletLayout
.prototype.isEditable = function () {
9975 return this.editable
;
9979 * Check if booklet has a visible outline.
9981 * @return {boolean} Outline is visible
9983 OO
.ui
.BookletLayout
.prototype.isOutlineVisible = function () {
9984 return this.outlined
&& this.outlineVisible
;
9988 * Hide or show the outline.
9990 * @param {boolean} [show] Show outline, omit to invert current state
9993 OO
.ui
.BookletLayout
.prototype.toggleOutline = function ( show
) {
9994 if ( this.outlined
) {
9995 show
= show
=== undefined ? !this.outlineVisible
: !!show
;
9996 this.outlineVisible
= show
;
9997 this.toggleMenu( show
);
10004 * Get the page closest to the specified page.
10006 * @param {OO.ui.PageLayout} page Page to use as a reference point
10007 * @return {OO.ui.PageLayout|null} Page closest to the specified page
10009 OO
.ui
.BookletLayout
.prototype.getClosestPage = function ( page
) {
10010 var next
, prev
, level
,
10011 pages
= this.stackLayout
.getItems(),
10012 index
= pages
.indexOf( page
);
10014 if ( index
!== -1 ) {
10015 next
= pages
[ index
+ 1 ];
10016 prev
= pages
[ index
- 1 ];
10017 // Prefer adjacent pages at the same level
10018 if ( this.outlined
) {
10019 level
= this.outlineSelectWidget
.getItemFromData( page
.getName() ).getLevel();
10022 level
=== this.outlineSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
10028 level
=== this.outlineSelectWidget
.getItemFromData( next
.getName() ).getLevel()
10034 return prev
|| next
|| null;
10038 * Get the outline widget.
10040 * If the booklet is not outlined, the method will return `null`.
10042 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
10044 OO
.ui
.BookletLayout
.prototype.getOutline = function () {
10045 return this.outlineSelectWidget
;
10049 * Get the outline controls widget.
10051 * If the outline is not editable, the method will return `null`.
10053 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
10055 OO
.ui
.BookletLayout
.prototype.getOutlineControls = function () {
10056 return this.outlineControlsWidget
;
10060 * Get a page by its symbolic name.
10062 * @param {string} name Symbolic name of page
10063 * @return {OO.ui.PageLayout|undefined} Page, if found
10065 OO
.ui
.BookletLayout
.prototype.getPage = function ( name
) {
10066 return this.pages
[ name
];
10070 * Get the current page.
10072 * @return {OO.ui.PageLayout|undefined} Current page, if found
10074 OO
.ui
.BookletLayout
.prototype.getCurrentPage = function () {
10075 var name
= this.getCurrentPageName();
10076 return name
? this.getPage( name
) : undefined;
10080 * Get the symbolic name of the current page.
10082 * @return {string|null} Symbolic name of the current page
10084 OO
.ui
.BookletLayout
.prototype.getCurrentPageName = function () {
10085 return this.currentPageName
;
10089 * Add pages to the booklet layout
10091 * When pages are added with the same names as existing pages, the existing pages will be
10092 * automatically removed before the new pages are added.
10094 * @param {OO.ui.PageLayout[]} pages Pages to add
10095 * @param {number} index Index of the insertion point
10099 OO
.ui
.BookletLayout
.prototype.addPages = function ( pages
, index
) {
10100 var i
, len
, name
, page
, item
, currentIndex
,
10101 stackLayoutPages
= this.stackLayout
.getItems(),
10105 // Remove pages with same names
10106 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
10108 name
= page
.getName();
10110 if ( Object
.prototype.hasOwnProperty
.call( this.pages
, name
) ) {
10111 // Correct the insertion index
10112 currentIndex
= stackLayoutPages
.indexOf( this.pages
[ name
] );
10113 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
10116 remove
.push( this.pages
[ name
] );
10119 if ( remove
.length
) {
10120 this.removePages( remove
);
10124 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
10126 name
= page
.getName();
10127 this.pages
[ page
.getName() ] = page
;
10128 if ( this.outlined
) {
10129 item
= new OO
.ui
.OutlineOptionWidget( { data
: name
} );
10130 page
.setOutlineItem( item
);
10131 items
.push( item
);
10135 if ( this.outlined
&& items
.length
) {
10136 this.outlineSelectWidget
.addItems( items
, index
);
10137 this.selectFirstSelectablePage();
10139 this.stackLayout
.addItems( pages
, index
);
10140 this.emit( 'add', pages
, index
);
10146 * Remove the specified pages from the booklet layout.
10148 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
10150 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
10154 OO
.ui
.BookletLayout
.prototype.removePages = function ( pages
) {
10155 var i
, len
, name
, page
,
10158 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
10160 name
= page
.getName();
10161 delete this.pages
[ name
];
10162 if ( this.outlined
) {
10163 items
.push( this.outlineSelectWidget
.getItemFromData( name
) );
10164 page
.setOutlineItem( null );
10167 if ( this.outlined
&& items
.length
) {
10168 this.outlineSelectWidget
.removeItems( items
);
10169 this.selectFirstSelectablePage();
10171 this.stackLayout
.removeItems( pages
);
10172 this.emit( 'remove', pages
);
10178 * Clear all pages from the booklet layout.
10180 * To remove only a subset of pages from the booklet, use the #removePages method.
10185 OO
.ui
.BookletLayout
.prototype.clearPages = function () {
10187 pages
= this.stackLayout
.getItems();
10190 this.currentPageName
= null;
10191 if ( this.outlined
) {
10192 this.outlineSelectWidget
.clearItems();
10193 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
10194 pages
[ i
].setOutlineItem( null );
10197 this.stackLayout
.clearItems();
10199 this.emit( 'remove', pages
);
10205 * Set the current page by symbolic name.
10208 * @param {string} name Symbolic name of page
10210 OO
.ui
.BookletLayout
.prototype.setPage = function ( name
) {
10213 page
= this.pages
[ name
],
10214 previousPage
= this.currentPageName
&& this.pages
[ this.currentPageName
];
10216 if ( name
!== this.currentPageName
) {
10217 if ( this.outlined
) {
10218 selectedItem
= this.outlineSelectWidget
.getSelectedItem();
10219 if ( selectedItem
&& selectedItem
.getData() !== name
) {
10220 this.outlineSelectWidget
.selectItemByData( name
);
10224 if ( previousPage
) {
10225 previousPage
.setActive( false );
10226 // Blur anything focused if the next page doesn't have anything focusable.
10227 // This is not needed if the next page has something focusable (because once it is focused
10228 // this blur happens automatically). If the layout is non-continuous, this check is
10229 // meaningless because the next page is not visible yet and thus can't hold focus.
10232 this.stackLayout
.continuous
&&
10233 OO
.ui
.findFocusable( page
.$element
).length
!== 0
10235 $focused
= previousPage
.$element
.find( ':focus' );
10236 if ( $focused
.length
) {
10237 $focused
[ 0 ].blur();
10241 this.currentPageName
= name
;
10242 page
.setActive( true );
10243 this.stackLayout
.setItem( page
);
10244 if ( !this.stackLayout
.continuous
&& previousPage
) {
10245 // This should not be necessary, since any inputs on the previous page should have been
10246 // blurred when it was hidden, but browsers are not very consistent about this.
10247 $focused
= previousPage
.$element
.find( ':focus' );
10248 if ( $focused
.length
) {
10249 $focused
[ 0 ].blur();
10252 this.emit( 'set', page
);
10258 * Select the first selectable page.
10262 OO
.ui
.BookletLayout
.prototype.selectFirstSelectablePage = function () {
10263 if ( !this.outlineSelectWidget
.getSelectedItem() ) {
10264 this.outlineSelectWidget
.selectItem( this.outlineSelectWidget
.getFirstSelectableItem() );
10271 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
10272 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
10273 * select which one to display. By default, only one card is displayed at a time. When a user
10274 * navigates to a new card, the index layout automatically focuses on the first focusable element,
10275 * unless the default setting is changed.
10277 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
10280 * // Example of a IndexLayout that contains two CardLayouts.
10282 * function CardOneLayout( name, config ) {
10283 * CardOneLayout.parent.call( this, name, config );
10284 * this.$element.append( '<p>First card</p>' );
10286 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
10287 * CardOneLayout.prototype.setupTabItem = function () {
10288 * this.tabItem.setLabel( 'Card one' );
10291 * var card1 = new CardOneLayout( 'one' ),
10292 * card2 = new CardLayout( 'two', { label: 'Card two' } );
10294 * card2.$element.append( '<p>Second card</p>' );
10296 * var index = new OO.ui.IndexLayout();
10298 * index.addCards ( [ card1, card2 ] );
10299 * $( 'body' ).append( index.$element );
10302 * @extends OO.ui.MenuLayout
10305 * @param {Object} [config] Configuration options
10306 * @cfg {boolean} [continuous=false] Show all cards, one after another
10307 * @cfg {boolean} [expanded=true] Expand the content panel to fill the entire parent element.
10308 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
10310 OO
.ui
.IndexLayout
= function OoUiIndexLayout( config
) {
10311 // Configuration initialization
10312 config
= $.extend( {}, config
, { menuPosition
: 'top' } );
10314 // Parent constructor
10315 OO
.ui
.IndexLayout
.parent
.call( this, config
);
10318 this.currentCardName
= null;
10320 this.ignoreFocus
= false;
10321 this.stackLayout
= new OO
.ui
.StackLayout( {
10322 continuous
: !!config
.continuous
,
10323 expanded
: config
.expanded
10325 this.$content
.append( this.stackLayout
.$element
);
10326 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
10328 this.tabSelectWidget
= new OO
.ui
.TabSelectWidget();
10329 this.tabPanel
= new OO
.ui
.PanelLayout();
10330 this.$menu
.append( this.tabPanel
.$element
);
10332 this.toggleMenu( true );
10335 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
10336 this.tabSelectWidget
.connect( this, { select
: 'onTabSelectWidgetSelect' } );
10337 if ( this.autoFocus
) {
10338 // Event 'focus' does not bubble, but 'focusin' does
10339 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
10343 this.$element
.addClass( 'oo-ui-indexLayout' );
10344 this.stackLayout
.$element
.addClass( 'oo-ui-indexLayout-stackLayout' );
10345 this.tabPanel
.$element
10346 .addClass( 'oo-ui-indexLayout-tabPanel' )
10347 .append( this.tabSelectWidget
.$element
);
10352 OO
.inheritClass( OO
.ui
.IndexLayout
, OO
.ui
.MenuLayout
);
10357 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
10359 * @param {OO.ui.CardLayout} card Current card
10363 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
10366 * @param {OO.ui.CardLayout[]} card Added cards
10367 * @param {number} index Index cards were added at
10371 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
10372 * {@link #removeCards removed} from the index.
10375 * @param {OO.ui.CardLayout[]} cards Removed cards
10381 * Handle stack layout focus.
10384 * @param {jQuery.Event} e Focusin event
10386 OO
.ui
.IndexLayout
.prototype.onStackLayoutFocus = function ( e
) {
10389 // Find the card that an element was focused within
10390 $target
= $( e
.target
).closest( '.oo-ui-cardLayout' );
10391 for ( name
in this.cards
) {
10392 // Check for card match, exclude current card to find only card changes
10393 if ( this.cards
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentCardName
) {
10394 this.setCard( name
);
10401 * Handle stack layout set events.
10404 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
10406 OO
.ui
.IndexLayout
.prototype.onStackLayoutSet = function ( card
) {
10409 card
.scrollElementIntoView( { complete: function () {
10410 if ( layout
.autoFocus
) {
10418 * Focus the first input in the current card.
10420 * If no card is selected, the first selectable card will be selected.
10421 * If the focus is already in an element on the current card, nothing will happen.
10422 * @param {number} [itemIndex] A specific item to focus on
10424 OO
.ui
.IndexLayout
.prototype.focus = function ( itemIndex
) {
10426 items
= this.stackLayout
.getItems();
10428 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
10429 card
= items
[ itemIndex
];
10431 card
= this.stackLayout
.getCurrentItem();
10435 this.selectFirstSelectableCard();
10436 card
= this.stackLayout
.getCurrentItem();
10441 // Only change the focus if is not already in the current page
10442 if ( !OO
.ui
.contains( card
.$element
[ 0 ], this.getElementDocument().activeElement
, true ) ) {
10448 * Find the first focusable input in the index layout and focus
10451 OO
.ui
.IndexLayout
.prototype.focusFirstFocusable = function () {
10452 OO
.ui
.findFocusable( this.stackLayout
.$element
).focus();
10456 * Handle tab widget select events.
10459 * @param {OO.ui.OptionWidget|null} item Selected item
10461 OO
.ui
.IndexLayout
.prototype.onTabSelectWidgetSelect = function ( item
) {
10463 this.setCard( item
.getData() );
10468 * Get the card closest to the specified card.
10470 * @param {OO.ui.CardLayout} card Card to use as a reference point
10471 * @return {OO.ui.CardLayout|null} Card closest to the specified card
10473 OO
.ui
.IndexLayout
.prototype.getClosestCard = function ( card
) {
10474 var next
, prev
, level
,
10475 cards
= this.stackLayout
.getItems(),
10476 index
= cards
.indexOf( card
);
10478 if ( index
!== -1 ) {
10479 next
= cards
[ index
+ 1 ];
10480 prev
= cards
[ index
- 1 ];
10481 // Prefer adjacent cards at the same level
10482 level
= this.tabSelectWidget
.getItemFromData( card
.getName() ).getLevel();
10485 level
=== this.tabSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
10491 level
=== this.tabSelectWidget
.getItemFromData( next
.getName() ).getLevel()
10496 return prev
|| next
|| null;
10500 * Get the tabs widget.
10502 * @return {OO.ui.TabSelectWidget} Tabs widget
10504 OO
.ui
.IndexLayout
.prototype.getTabs = function () {
10505 return this.tabSelectWidget
;
10509 * Get a card by its symbolic name.
10511 * @param {string} name Symbolic name of card
10512 * @return {OO.ui.CardLayout|undefined} Card, if found
10514 OO
.ui
.IndexLayout
.prototype.getCard = function ( name
) {
10515 return this.cards
[ name
];
10519 * Get the current card.
10521 * @return {OO.ui.CardLayout|undefined} Current card, if found
10523 OO
.ui
.IndexLayout
.prototype.getCurrentCard = function () {
10524 var name
= this.getCurrentCardName();
10525 return name
? this.getCard( name
) : undefined;
10529 * Get the symbolic name of the current card.
10531 * @return {string|null} Symbolic name of the current card
10533 OO
.ui
.IndexLayout
.prototype.getCurrentCardName = function () {
10534 return this.currentCardName
;
10538 * Add cards to the index layout
10540 * When cards are added with the same names as existing cards, the existing cards will be
10541 * automatically removed before the new cards are added.
10543 * @param {OO.ui.CardLayout[]} cards Cards to add
10544 * @param {number} index Index of the insertion point
10548 OO
.ui
.IndexLayout
.prototype.addCards = function ( cards
, index
) {
10549 var i
, len
, name
, card
, item
, currentIndex
,
10550 stackLayoutCards
= this.stackLayout
.getItems(),
10554 // Remove cards with same names
10555 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10557 name
= card
.getName();
10559 if ( Object
.prototype.hasOwnProperty
.call( this.cards
, name
) ) {
10560 // Correct the insertion index
10561 currentIndex
= stackLayoutCards
.indexOf( this.cards
[ name
] );
10562 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
10565 remove
.push( this.cards
[ name
] );
10568 if ( remove
.length
) {
10569 this.removeCards( remove
);
10573 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10575 name
= card
.getName();
10576 this.cards
[ card
.getName() ] = card
;
10577 item
= new OO
.ui
.TabOptionWidget( { data
: name
} );
10578 card
.setTabItem( item
);
10579 items
.push( item
);
10582 if ( items
.length
) {
10583 this.tabSelectWidget
.addItems( items
, index
);
10584 this.selectFirstSelectableCard();
10586 this.stackLayout
.addItems( cards
, index
);
10587 this.emit( 'add', cards
, index
);
10593 * Remove the specified cards from the index layout.
10595 * To remove all cards from the index, you may wish to use the #clearCards method instead.
10597 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
10601 OO
.ui
.IndexLayout
.prototype.removeCards = function ( cards
) {
10602 var i
, len
, name
, card
,
10605 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10607 name
= card
.getName();
10608 delete this.cards
[ name
];
10609 items
.push( this.tabSelectWidget
.getItemFromData( name
) );
10610 card
.setTabItem( null );
10612 if ( items
.length
) {
10613 this.tabSelectWidget
.removeItems( items
);
10614 this.selectFirstSelectableCard();
10616 this.stackLayout
.removeItems( cards
);
10617 this.emit( 'remove', cards
);
10623 * Clear all cards from the index layout.
10625 * To remove only a subset of cards from the index, use the #removeCards method.
10630 OO
.ui
.IndexLayout
.prototype.clearCards = function () {
10632 cards
= this.stackLayout
.getItems();
10635 this.currentCardName
= null;
10636 this.tabSelectWidget
.clearItems();
10637 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10638 cards
[ i
].setTabItem( null );
10640 this.stackLayout
.clearItems();
10642 this.emit( 'remove', cards
);
10648 * Set the current card by symbolic name.
10651 * @param {string} name Symbolic name of card
10653 OO
.ui
.IndexLayout
.prototype.setCard = function ( name
) {
10656 card
= this.cards
[ name
],
10657 previousCard
= this.currentCardName
&& this.cards
[ this.currentCardName
];
10659 if ( name
!== this.currentCardName
) {
10660 selectedItem
= this.tabSelectWidget
.getSelectedItem();
10661 if ( selectedItem
&& selectedItem
.getData() !== name
) {
10662 this.tabSelectWidget
.selectItemByData( name
);
10665 if ( previousCard
) {
10666 previousCard
.setActive( false );
10667 // Blur anything focused if the next card doesn't have anything focusable.
10668 // This is not needed if the next card has something focusable (because once it is focused
10669 // this blur happens automatically). If the layout is non-continuous, this check is
10670 // meaningless because the next card is not visible yet and thus can't hold focus.
10673 this.stackLayout
.continuous
&&
10674 OO
.ui
.findFocusable( card
.$element
).length
!== 0
10676 $focused
= previousCard
.$element
.find( ':focus' );
10677 if ( $focused
.length
) {
10678 $focused
[ 0 ].blur();
10682 this.currentCardName
= name
;
10683 card
.setActive( true );
10684 this.stackLayout
.setItem( card
);
10685 if ( !this.stackLayout
.continuous
&& previousCard
) {
10686 // This should not be necessary, since any inputs on the previous card should have been
10687 // blurred when it was hidden, but browsers are not very consistent about this.
10688 $focused
= previousCard
.$element
.find( ':focus' );
10689 if ( $focused
.length
) {
10690 $focused
[ 0 ].blur();
10693 this.emit( 'set', card
);
10699 * Select the first selectable card.
10703 OO
.ui
.IndexLayout
.prototype.selectFirstSelectableCard = function () {
10704 if ( !this.tabSelectWidget
.getSelectedItem() ) {
10705 this.tabSelectWidget
.selectItem( this.tabSelectWidget
.getFirstSelectableItem() );
10712 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10713 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10716 * // Example of a panel layout
10717 * var panel = new OO.ui.PanelLayout( {
10721 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10723 * $( 'body' ).append( panel.$element );
10726 * @extends OO.ui.Layout
10729 * @param {Object} [config] Configuration options
10730 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10731 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10732 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10733 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10735 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
10736 // Configuration initialization
10737 config
= $.extend( {
10744 // Parent constructor
10745 OO
.ui
.PanelLayout
.parent
.call( this, config
);
10748 this.$element
.addClass( 'oo-ui-panelLayout' );
10749 if ( config
.scrollable
) {
10750 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
10752 if ( config
.padded
) {
10753 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
10755 if ( config
.expanded
) {
10756 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
10758 if ( config
.framed
) {
10759 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
10765 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
10770 * Focus the panel layout
10772 * The default implementation just focuses the first focusable element in the panel
10774 OO
.ui
.PanelLayout
.prototype.focus = function () {
10775 OO
.ui
.findFocusable( this.$element
).focus();
10779 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
10780 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
10781 * rather extended to include the required content and functionality.
10783 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
10784 * item is customized (with a label) using the #setupTabItem method. See
10785 * {@link OO.ui.IndexLayout IndexLayout} for an example.
10788 * @extends OO.ui.PanelLayout
10791 * @param {string} name Unique symbolic name of card
10792 * @param {Object} [config] Configuration options
10793 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] Label for card's tab
10795 OO
.ui
.CardLayout
= function OoUiCardLayout( name
, config
) {
10796 // Allow passing positional parameters inside the config object
10797 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
10799 name
= config
.name
;
10802 // Configuration initialization
10803 config
= $.extend( { scrollable
: true }, config
);
10805 // Parent constructor
10806 OO
.ui
.CardLayout
.parent
.call( this, config
);
10810 this.label
= config
.label
;
10811 this.tabItem
= null;
10812 this.active
= false;
10815 this.$element
.addClass( 'oo-ui-cardLayout' );
10820 OO
.inheritClass( OO
.ui
.CardLayout
, OO
.ui
.PanelLayout
);
10825 * An 'active' event is emitted when the card becomes active. Cards become active when they are
10826 * shown in a index layout that is configured to display only one card at a time.
10829 * @param {boolean} active Card is active
10835 * Get the symbolic name of the card.
10837 * @return {string} Symbolic name of card
10839 OO
.ui
.CardLayout
.prototype.getName = function () {
10844 * Check if card is active.
10846 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
10847 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
10849 * @return {boolean} Card is active
10851 OO
.ui
.CardLayout
.prototype.isActive = function () {
10852 return this.active
;
10858 * The tab item allows users to access the card from the index's tab
10859 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
10861 * @return {OO.ui.TabOptionWidget|null} Tab option widget
10863 OO
.ui
.CardLayout
.prototype.getTabItem = function () {
10864 return this.tabItem
;
10868 * Set or unset the tab item.
10870 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
10871 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
10872 * level), use #setupTabItem instead of this method.
10874 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
10877 OO
.ui
.CardLayout
.prototype.setTabItem = function ( tabItem
) {
10878 this.tabItem
= tabItem
|| null;
10880 this.setupTabItem();
10886 * Set up the tab item.
10888 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
10889 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
10890 * the #setTabItem method instead.
10892 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
10895 OO
.ui
.CardLayout
.prototype.setupTabItem = function () {
10896 if ( this.label
) {
10897 this.tabItem
.setLabel( this.label
);
10903 * Set the card to its 'active' state.
10905 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
10906 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
10907 * context, setting the active state on a card does nothing.
10909 * @param {boolean} value Card is active
10912 OO
.ui
.CardLayout
.prototype.setActive = function ( active
) {
10915 if ( active
!== this.active
) {
10916 this.active
= active
;
10917 this.$element
.toggleClass( 'oo-ui-cardLayout-active', this.active
);
10918 this.emit( 'active', this.active
);
10923 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
10924 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
10925 * rather extended to include the required content and functionality.
10927 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
10928 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
10929 * {@link OO.ui.BookletLayout BookletLayout} for an example.
10932 * @extends OO.ui.PanelLayout
10935 * @param {string} name Unique symbolic name of page
10936 * @param {Object} [config] Configuration options
10938 OO
.ui
.PageLayout
= function OoUiPageLayout( name
, config
) {
10939 // Allow passing positional parameters inside the config object
10940 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
10942 name
= config
.name
;
10945 // Configuration initialization
10946 config
= $.extend( { scrollable
: true }, config
);
10948 // Parent constructor
10949 OO
.ui
.PageLayout
.parent
.call( this, config
);
10953 this.outlineItem
= null;
10954 this.active
= false;
10957 this.$element
.addClass( 'oo-ui-pageLayout' );
10962 OO
.inheritClass( OO
.ui
.PageLayout
, OO
.ui
.PanelLayout
);
10967 * An 'active' event is emitted when the page becomes active. Pages become active when they are
10968 * shown in a booklet layout that is configured to display only one page at a time.
10971 * @param {boolean} active Page is active
10977 * Get the symbolic name of the page.
10979 * @return {string} Symbolic name of page
10981 OO
.ui
.PageLayout
.prototype.getName = function () {
10986 * Check if page is active.
10988 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
10989 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
10991 * @return {boolean} Page is active
10993 OO
.ui
.PageLayout
.prototype.isActive = function () {
10994 return this.active
;
10998 * Get outline item.
11000 * The outline item allows users to access the page from the booklet's outline
11001 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
11003 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
11005 OO
.ui
.PageLayout
.prototype.getOutlineItem = function () {
11006 return this.outlineItem
;
11010 * Set or unset the outline item.
11012 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
11013 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
11014 * level), use #setupOutlineItem instead of this method.
11016 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
11019 OO
.ui
.PageLayout
.prototype.setOutlineItem = function ( outlineItem
) {
11020 this.outlineItem
= outlineItem
|| null;
11021 if ( outlineItem
) {
11022 this.setupOutlineItem();
11028 * Set up the outline item.
11030 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
11031 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
11032 * the #setOutlineItem method instead.
11034 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
11037 OO
.ui
.PageLayout
.prototype.setupOutlineItem = function () {
11042 * Set the page to its 'active' state.
11044 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
11045 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
11046 * context, setting the active state on a page does nothing.
11048 * @param {boolean} value Page is active
11051 OO
.ui
.PageLayout
.prototype.setActive = function ( active
) {
11054 if ( active
!== this.active
) {
11055 this.active
= active
;
11056 this.$element
.toggleClass( 'oo-ui-pageLayout-active', active
);
11057 this.emit( 'active', this.active
);
11062 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
11063 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
11064 * by setting the #continuous option to 'true'.
11067 * // A stack layout with two panels, configured to be displayed continously
11068 * var myStack = new OO.ui.StackLayout( {
11070 * new OO.ui.PanelLayout( {
11071 * $content: $( '<p>Panel One</p>' ),
11075 * new OO.ui.PanelLayout( {
11076 * $content: $( '<p>Panel Two</p>' ),
11083 * $( 'body' ).append( myStack.$element );
11086 * @extends OO.ui.PanelLayout
11087 * @mixins OO.ui.mixin.GroupElement
11090 * @param {Object} [config] Configuration options
11091 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
11092 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
11094 OO
.ui
.StackLayout
= function OoUiStackLayout( config
) {
11095 // Configuration initialization
11096 config
= $.extend( { scrollable
: true }, config
);
11098 // Parent constructor
11099 OO
.ui
.StackLayout
.parent
.call( this, config
);
11101 // Mixin constructors
11102 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11105 this.currentItem
= null;
11106 this.continuous
= !!config
.continuous
;
11109 this.$element
.addClass( 'oo-ui-stackLayout' );
11110 if ( this.continuous
) {
11111 this.$element
.addClass( 'oo-ui-stackLayout-continuous' );
11112 this.$element
.on( 'scroll', OO
.ui
.debounce( this.onScroll
.bind( this ), 250 ) );
11114 if ( Array
.isArray( config
.items
) ) {
11115 this.addItems( config
.items
);
11121 OO
.inheritClass( OO
.ui
.StackLayout
, OO
.ui
.PanelLayout
);
11122 OO
.mixinClass( OO
.ui
.StackLayout
, OO
.ui
.mixin
.GroupElement
);
11127 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
11128 * {@link #clearItems cleared} or {@link #setItem displayed}.
11131 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
11135 * When used in continuous mode, this event is emitted when the user scrolls down
11136 * far enough such that currentItem is no longer visible.
11138 * @event visibleItemChange
11139 * @param {OO.ui.PanelLayout} panel The next visible item in the layout
11145 * Handle scroll events from the layout element
11147 * @param {jQuery.Event} e
11148 * @fires visibleItemChange
11150 OO
.ui
.StackLayout
.prototype.onScroll = function () {
11152 len
= this.items
.length
,
11153 currentIndex
= this.items
.indexOf( this.currentItem
),
11154 newIndex
= currentIndex
,
11155 containerRect
= this.$element
[ 0 ].getBoundingClientRect();
11157 if ( !containerRect
|| ( !containerRect
.top
&& !containerRect
.bottom
) ) {
11158 // Can't get bounding rect, possibly not attached.
11162 function getRect( item
) {
11163 return item
.$element
[ 0 ].getBoundingClientRect();
11166 function isVisible( item
) {
11167 var rect
= getRect( item
);
11168 return rect
.bottom
> containerRect
.top
&& rect
.top
< containerRect
.bottom
;
11171 currentRect
= getRect( this.currentItem
);
11173 if ( currentRect
.bottom
< containerRect
.top
) {
11174 // Scrolled down past current item
11175 while ( ++newIndex
< len
) {
11176 if ( isVisible( this.items
[ newIndex
] ) ) {
11180 } else if ( currentRect
.top
> containerRect
.bottom
) {
11181 // Scrolled up past current item
11182 while ( --newIndex
>= 0 ) {
11183 if ( isVisible( this.items
[ newIndex
] ) ) {
11189 if ( newIndex
!== currentIndex
) {
11190 this.emit( 'visibleItemChange', this.items
[ newIndex
] );
11195 * Get the current panel.
11197 * @return {OO.ui.Layout|null}
11199 OO
.ui
.StackLayout
.prototype.getCurrentItem = function () {
11200 return this.currentItem
;
11204 * Unset the current item.
11207 * @param {OO.ui.StackLayout} layout
11210 OO
.ui
.StackLayout
.prototype.unsetCurrentItem = function () {
11211 var prevItem
= this.currentItem
;
11212 if ( prevItem
=== null ) {
11216 this.currentItem
= null;
11217 this.emit( 'set', null );
11221 * Add panel layouts to the stack layout.
11223 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
11224 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
11227 * @param {OO.ui.Layout[]} items Panels to add
11228 * @param {number} [index] Index of the insertion point
11231 OO
.ui
.StackLayout
.prototype.addItems = function ( items
, index
) {
11232 // Update the visibility
11233 this.updateHiddenState( items
, this.currentItem
);
11236 OO
.ui
.mixin
.GroupElement
.prototype.addItems
.call( this, items
, index
);
11238 if ( !this.currentItem
&& items
.length
) {
11239 this.setItem( items
[ 0 ] );
11246 * Remove the specified panels from the stack layout.
11248 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
11249 * you may wish to use the #clearItems method instead.
11251 * @param {OO.ui.Layout[]} items Panels to remove
11255 OO
.ui
.StackLayout
.prototype.removeItems = function ( items
) {
11257 OO
.ui
.mixin
.GroupElement
.prototype.removeItems
.call( this, items
);
11259 if ( items
.indexOf( this.currentItem
) !== -1 ) {
11260 if ( this.items
.length
) {
11261 this.setItem( this.items
[ 0 ] );
11263 this.unsetCurrentItem();
11271 * Clear all panels from the stack layout.
11273 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
11274 * a subset of panels, use the #removeItems method.
11279 OO
.ui
.StackLayout
.prototype.clearItems = function () {
11280 this.unsetCurrentItem();
11281 OO
.ui
.mixin
.GroupElement
.prototype.clearItems
.call( this );
11287 * Show the specified panel.
11289 * If another panel is currently displayed, it will be hidden.
11291 * @param {OO.ui.Layout} item Panel to show
11295 OO
.ui
.StackLayout
.prototype.setItem = function ( item
) {
11296 if ( item
!== this.currentItem
) {
11297 this.updateHiddenState( this.items
, item
);
11299 if ( this.items
.indexOf( item
) !== -1 ) {
11300 this.currentItem
= item
;
11301 this.emit( 'set', item
);
11303 this.unsetCurrentItem();
11311 * Update the visibility of all items in case of non-continuous view.
11313 * Ensure all items are hidden except for the selected one.
11314 * This method does nothing when the stack is continuous.
11317 * @param {OO.ui.Layout[]} items Item list iterate over
11318 * @param {OO.ui.Layout} [selectedItem] Selected item to show
11320 OO
.ui
.StackLayout
.prototype.updateHiddenState = function ( items
, selectedItem
) {
11323 if ( !this.continuous
) {
11324 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
11325 if ( !selectedItem
|| selectedItem
!== items
[ i
] ) {
11326 items
[ i
].$element
.addClass( 'oo-ui-element-hidden' );
11329 if ( selectedItem
) {
11330 selectedItem
.$element
.removeClass( 'oo-ui-element-hidden' );
11336 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
11337 * items), with small margins between them. Convenient when you need to put a number of block-level
11338 * widgets on a single line next to each other.
11340 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
11343 * // HorizontalLayout with a text input and a label
11344 * var layout = new OO.ui.HorizontalLayout( {
11346 * new OO.ui.LabelWidget( { label: 'Label' } ),
11347 * new OO.ui.TextInputWidget( { value: 'Text' } )
11350 * $( 'body' ).append( layout.$element );
11353 * @extends OO.ui.Layout
11354 * @mixins OO.ui.mixin.GroupElement
11357 * @param {Object} [config] Configuration options
11358 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
11360 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
11361 // Configuration initialization
11362 config
= config
|| {};
11364 // Parent constructor
11365 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
11367 // Mixin constructors
11368 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11371 this.$element
.addClass( 'oo-ui-horizontalLayout' );
11372 if ( Array
.isArray( config
.items
) ) {
11373 this.addItems( config
.items
);
11379 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
11380 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);
11383 * BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11384 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11385 * and {@link OO.ui.ListToolGroup ListToolGroup}). The {@link OO.ui.Tool tools} in a BarToolGroup are
11386 * displayed by icon in a single row. The title of the tool is displayed when users move the mouse over
11389 * BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar is
11393 * // Example of a BarToolGroup with two tools
11394 * var toolFactory = new OO.ui.ToolFactory();
11395 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11396 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11398 * // We will be placing status text in this element when tools are used
11399 * var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' );
11401 * // Define the tools that we're going to place in our toolbar
11403 * // Create a class inheriting from OO.ui.Tool
11404 * function PictureTool() {
11405 * PictureTool.parent.apply( this, arguments );
11407 * OO.inheritClass( PictureTool, OO.ui.Tool );
11408 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
11409 * // of 'icon' and 'title' (displayed icon and text).
11410 * PictureTool.static.name = 'picture';
11411 * PictureTool.static.icon = 'picture';
11412 * PictureTool.static.title = 'Insert picture';
11413 * // Defines the action that will happen when this tool is selected (clicked).
11414 * PictureTool.prototype.onSelect = function () {
11415 * $area.text( 'Picture tool clicked!' );
11416 * // Never display this tool as "active" (selected).
11417 * this.setActive( false );
11419 * // Make this tool available in our toolFactory and thus our toolbar
11420 * toolFactory.register( PictureTool );
11422 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
11423 * // little popup window (a PopupWidget).
11424 * function HelpTool( toolGroup, config ) {
11425 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11430 * this.popup.$body.append( '<p>I am helpful!</p>' );
11432 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11433 * HelpTool.static.name = 'help';
11434 * HelpTool.static.icon = 'help';
11435 * HelpTool.static.title = 'Help';
11436 * toolFactory.register( HelpTool );
11438 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11439 * // used once (but not all defined tools must be used).
11442 * // 'bar' tool groups display tools by icon only
11444 * include: [ 'picture', 'help' ]
11448 * // Create some UI around the toolbar and place it in the document
11449 * var frame = new OO.ui.PanelLayout( {
11453 * var contentFrame = new OO.ui.PanelLayout( {
11457 * frame.$element.append(
11458 * toolbar.$element,
11459 * contentFrame.$element.append( $area )
11461 * $( 'body' ).append( frame.$element );
11463 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11465 * toolbar.initialize();
11467 * For more information about how to add tools to a bar tool group, please see {@link OO.ui.ToolGroup toolgroup}.
11468 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11470 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11473 * @extends OO.ui.ToolGroup
11476 * @param {OO.ui.Toolbar} toolbar
11477 * @param {Object} [config] Configuration options
11479 OO
.ui
.BarToolGroup
= function OoUiBarToolGroup( toolbar
, config
) {
11480 // Allow passing positional parameters inside the config object
11481 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11483 toolbar
= config
.toolbar
;
11486 // Parent constructor
11487 OO
.ui
.BarToolGroup
.parent
.call( this, toolbar
, config
);
11490 this.$element
.addClass( 'oo-ui-barToolGroup' );
11495 OO
.inheritClass( OO
.ui
.BarToolGroup
, OO
.ui
.ToolGroup
);
11497 /* Static Properties */
11499 OO
.ui
.BarToolGroup
.static.titleTooltips
= true;
11501 OO
.ui
.BarToolGroup
.static.accelTooltips
= true;
11503 OO
.ui
.BarToolGroup
.static.name
= 'bar';
11506 * PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup}
11507 * and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup--an overlaid menu or list of tools with an
11508 * optional icon and label. This class can be used for other base classes that also use this functionality.
11512 * @extends OO.ui.ToolGroup
11513 * @mixins OO.ui.mixin.IconElement
11514 * @mixins OO.ui.mixin.IndicatorElement
11515 * @mixins OO.ui.mixin.LabelElement
11516 * @mixins OO.ui.mixin.TitledElement
11517 * @mixins OO.ui.mixin.ClippableElement
11518 * @mixins OO.ui.mixin.TabIndexedElement
11521 * @param {OO.ui.Toolbar} toolbar
11522 * @param {Object} [config] Configuration options
11523 * @cfg {string} [header] Text to display at the top of the popup
11525 OO
.ui
.PopupToolGroup
= function OoUiPopupToolGroup( toolbar
, config
) {
11526 // Allow passing positional parameters inside the config object
11527 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11529 toolbar
= config
.toolbar
;
11532 // Configuration initialization
11533 config
= config
|| {};
11535 // Parent constructor
11536 OO
.ui
.PopupToolGroup
.parent
.call( this, toolbar
, config
);
11539 this.active
= false;
11540 this.dragging
= false;
11541 this.onBlurHandler
= this.onBlur
.bind( this );
11542 this.$handle
= $( '<span>' );
11544 // Mixin constructors
11545 OO
.ui
.mixin
.IconElement
.call( this, config
);
11546 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
11547 OO
.ui
.mixin
.LabelElement
.call( this, config
);
11548 OO
.ui
.mixin
.TitledElement
.call( this, config
);
11549 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
11550 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
11554 keydown
: this.onHandleMouseKeyDown
.bind( this ),
11555 keyup
: this.onHandleMouseKeyUp
.bind( this ),
11556 mousedown
: this.onHandleMouseKeyDown
.bind( this ),
11557 mouseup
: this.onHandleMouseKeyUp
.bind( this )
11562 .addClass( 'oo-ui-popupToolGroup-handle' )
11563 .append( this.$icon
, this.$label
, this.$indicator
);
11564 // If the pop-up should have a header, add it to the top of the toolGroup.
11565 // Note: If this feature is useful for other widgets, we could abstract it into an
11566 // OO.ui.HeaderedElement mixin constructor.
11567 if ( config
.header
!== undefined ) {
11569 .prepend( $( '<span>' )
11570 .addClass( 'oo-ui-popupToolGroup-header' )
11571 .text( config
.header
)
11575 .addClass( 'oo-ui-popupToolGroup' )
11576 .prepend( this.$handle
);
11581 OO
.inheritClass( OO
.ui
.PopupToolGroup
, OO
.ui
.ToolGroup
);
11582 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.IconElement
);
11583 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.IndicatorElement
);
11584 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.LabelElement
);
11585 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.TitledElement
);
11586 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.ClippableElement
);
11587 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.TabIndexedElement
);
11594 OO
.ui
.PopupToolGroup
.prototype.setDisabled = function () {
11596 OO
.ui
.PopupToolGroup
.parent
.prototype.setDisabled
.apply( this, arguments
);
11598 if ( this.isDisabled() && this.isElementAttached() ) {
11599 this.setActive( false );
11604 * Handle focus being lost.
11606 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
11609 * @param {jQuery.Event} e Mouse up or key up event
11611 OO
.ui
.PopupToolGroup
.prototype.onBlur = function ( e
) {
11612 // Only deactivate when clicking outside the dropdown element
11613 if ( $( e
.target
).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element
[ 0 ] ) {
11614 this.setActive( false );
11621 OO
.ui
.PopupToolGroup
.prototype.onMouseKeyUp = function ( e
) {
11622 // Only close toolgroup when a tool was actually selected
11624 !this.isDisabled() && this.pressed
&& this.pressed
=== this.getTargetTool( e
) &&
11625 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11627 this.setActive( false );
11629 return OO
.ui
.PopupToolGroup
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11633 * Handle mouse up and key up events.
11636 * @param {jQuery.Event} e Mouse up or key up event
11638 OO
.ui
.PopupToolGroup
.prototype.onHandleMouseKeyUp = function ( e
) {
11640 !this.isDisabled() &&
11641 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11648 * Handle mouse down and key down events.
11651 * @param {jQuery.Event} e Mouse down or key down event
11653 OO
.ui
.PopupToolGroup
.prototype.onHandleMouseKeyDown = function ( e
) {
11655 !this.isDisabled() &&
11656 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11658 this.setActive( !this.active
);
11664 * Switch into 'active' mode.
11666 * When active, the popup is visible. A mouseup event anywhere in the document will trigger
11669 OO
.ui
.PopupToolGroup
.prototype.setActive = function ( value
) {
11670 var containerWidth
, containerLeft
;
11672 if ( this.active
!== value
) {
11673 this.active
= value
;
11675 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler
);
11676 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler
);
11678 this.$clippable
.css( 'left', '' );
11679 // Try anchoring the popup to the left first
11680 this.$element
.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
11681 this.toggleClipping( true );
11682 if ( this.isClippedHorizontally() ) {
11683 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
11684 this.toggleClipping( false );
11686 .removeClass( 'oo-ui-popupToolGroup-left' )
11687 .addClass( 'oo-ui-popupToolGroup-right' );
11688 this.toggleClipping( true );
11690 if ( this.isClippedHorizontally() ) {
11691 // Anchoring to the right also caused the popup to clip, so just make it fill the container
11692 containerWidth
= this.$clippableScrollableContainer
.width();
11693 containerLeft
= this.$clippableScrollableContainer
.offset().left
;
11695 this.toggleClipping( false );
11696 this.$element
.removeClass( 'oo-ui-popupToolGroup-right' );
11698 this.$clippable
.css( {
11699 left
: -( this.$element
.offset().left
- containerLeft
),
11700 width
: containerWidth
11704 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler
);
11705 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler
);
11706 this.$element
.removeClass(
11707 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
11709 this.toggleClipping( false );
11715 * ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11716 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11717 * and {@link OO.ui.BarToolGroup BarToolGroup}). The {@link OO.ui.Tool tools} in a ListToolGroup are displayed
11718 * by label in a dropdown menu. The title of the tool is used as the label text. The menu itself can be configured
11719 * with a label, icon, indicator, header, and title.
11721 * ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a ‘More’ option that
11722 * users can select to see the full list of tools. If a collapsed toolgroup is expanded, a ‘Fewer’ option permits
11723 * users to collapse the list again.
11725 * ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the toolbar is set up. The factory
11726 * requires the ListToolGroup's symbolic name, 'list', which is specified along with the other configurations. For more
11727 * information about how to add tools to a ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11730 * // Example of a ListToolGroup
11731 * var toolFactory = new OO.ui.ToolFactory();
11732 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11733 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11735 * // Configure and register two tools
11736 * function SettingsTool() {
11737 * SettingsTool.parent.apply( this, arguments );
11739 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11740 * SettingsTool.static.name = 'settings';
11741 * SettingsTool.static.icon = 'settings';
11742 * SettingsTool.static.title = 'Change settings';
11743 * SettingsTool.prototype.onSelect = function () {
11744 * this.setActive( false );
11746 * toolFactory.register( SettingsTool );
11747 * // Register two more tools, nothing interesting here
11748 * function StuffTool() {
11749 * StuffTool.parent.apply( this, arguments );
11751 * OO.inheritClass( StuffTool, OO.ui.Tool );
11752 * StuffTool.static.name = 'stuff';
11753 * StuffTool.static.icon = 'ellipsis';
11754 * StuffTool.static.title = 'Change the world';
11755 * StuffTool.prototype.onSelect = function () {
11756 * this.setActive( false );
11758 * toolFactory.register( StuffTool );
11761 * // Configurations for list toolgroup.
11763 * label: 'ListToolGroup',
11764 * indicator: 'down',
11766 * title: 'This is the title, displayed when user moves the mouse over the list toolgroup',
11767 * header: 'This is the header',
11768 * include: [ 'settings', 'stuff' ],
11769 * allowCollapse: ['stuff']
11773 * // Create some UI around the toolbar and place it in the document
11774 * var frame = new OO.ui.PanelLayout( {
11778 * frame.$element.append(
11781 * $( 'body' ).append( frame.$element );
11782 * // Build the toolbar. This must be done after the toolbar has been appended to the document.
11783 * toolbar.initialize();
11785 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11787 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11790 * @extends OO.ui.PopupToolGroup
11793 * @param {OO.ui.Toolbar} toolbar
11794 * @param {Object} [config] Configuration options
11795 * @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible tools
11796 * will only be displayed if users click the ‘More’ option displayed at the bottom of the list. If
11797 * the list is expanded, a ‘Fewer’ option permits users to collapse the list again. Any tools that
11798 * are included in the toolgroup, but are not designated as collapsible, will always be displayed.
11799 * To open a collapsible list in its expanded state, set #expanded to 'true'.
11800 * @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as collapsible.
11801 * Unless #expanded is set to true, the collapsible tools will be collapsed when the list is first opened.
11802 * @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools have
11803 * been designated as collapsible. When expanded is set to true, all tools in the group will be displayed
11804 * when the list is first opened. Users can collapse the list with a ‘Fewer’ option at the bottom.
11806 OO
.ui
.ListToolGroup
= function OoUiListToolGroup( toolbar
, config
) {
11807 // Allow passing positional parameters inside the config object
11808 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11810 toolbar
= config
.toolbar
;
11813 // Configuration initialization
11814 config
= config
|| {};
11816 // Properties (must be set before parent constructor, which calls #populate)
11817 this.allowCollapse
= config
.allowCollapse
;
11818 this.forceExpand
= config
.forceExpand
;
11819 this.expanded
= config
.expanded
!== undefined ? config
.expanded
: false;
11820 this.collapsibleTools
= [];
11822 // Parent constructor
11823 OO
.ui
.ListToolGroup
.parent
.call( this, toolbar
, config
);
11826 this.$element
.addClass( 'oo-ui-listToolGroup' );
11831 OO
.inheritClass( OO
.ui
.ListToolGroup
, OO
.ui
.PopupToolGroup
);
11833 /* Static Properties */
11835 OO
.ui
.ListToolGroup
.static.name
= 'list';
11842 OO
.ui
.ListToolGroup
.prototype.populate = function () {
11843 var i
, len
, allowCollapse
= [];
11845 OO
.ui
.ListToolGroup
.parent
.prototype.populate
.call( this );
11847 // Update the list of collapsible tools
11848 if ( this.allowCollapse
!== undefined ) {
11849 allowCollapse
= this.allowCollapse
;
11850 } else if ( this.forceExpand
!== undefined ) {
11851 allowCollapse
= OO
.simpleArrayDifference( Object
.keys( this.tools
), this.forceExpand
);
11854 this.collapsibleTools
= [];
11855 for ( i
= 0, len
= allowCollapse
.length
; i
< len
; i
++ ) {
11856 if ( this.tools
[ allowCollapse
[ i
] ] !== undefined ) {
11857 this.collapsibleTools
.push( this.tools
[ allowCollapse
[ i
] ] );
11861 // Keep at the end, even when tools are added
11862 this.$group
.append( this.getExpandCollapseTool().$element
);
11864 this.getExpandCollapseTool().toggle( this.collapsibleTools
.length
!== 0 );
11865 this.updateCollapsibleState();
11868 OO
.ui
.ListToolGroup
.prototype.getExpandCollapseTool = function () {
11869 var ExpandCollapseTool
;
11870 if ( this.expandCollapseTool
=== undefined ) {
11871 ExpandCollapseTool = function () {
11872 ExpandCollapseTool
.parent
.apply( this, arguments
);
11875 OO
.inheritClass( ExpandCollapseTool
, OO
.ui
.Tool
);
11877 ExpandCollapseTool
.prototype.onSelect = function () {
11878 this.toolGroup
.expanded
= !this.toolGroup
.expanded
;
11879 this.toolGroup
.updateCollapsibleState();
11880 this.setActive( false );
11882 ExpandCollapseTool
.prototype.onUpdateState = function () {
11883 // Do nothing. Tool interface requires an implementation of this function.
11886 ExpandCollapseTool
.static.name
= 'more-fewer';
11888 this.expandCollapseTool
= new ExpandCollapseTool( this );
11890 return this.expandCollapseTool
;
11896 OO
.ui
.ListToolGroup
.prototype.onMouseKeyUp = function ( e
) {
11897 // Do not close the popup when the user wants to show more/fewer tools
11899 $( e
.target
).closest( '.oo-ui-tool-name-more-fewer' ).length
&&
11900 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11902 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
11903 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
11904 return OO
.ui
.ListToolGroup
.parent
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11906 return OO
.ui
.ListToolGroup
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11910 OO
.ui
.ListToolGroup
.prototype.updateCollapsibleState = function () {
11913 this.getExpandCollapseTool()
11914 .setIcon( this.expanded
? 'collapse' : 'expand' )
11915 .setTitle( OO
.ui
.msg( this.expanded
? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
11917 for ( i
= 0, len
= this.collapsibleTools
.length
; i
< len
; i
++ ) {
11918 this.collapsibleTools
[ i
].toggle( this.expanded
);
11923 * MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11924 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.BarToolGroup BarToolGroup}
11925 * and {@link OO.ui.ListToolGroup ListToolGroup}). MenuToolGroups contain selectable {@link OO.ui.Tool tools},
11926 * which are displayed by label in a dropdown menu. The tool's title is used as the label text, and the
11927 * menu label is updated to reflect which tool or tools are currently selected. If no tools are selected,
11928 * the menu label is empty. The menu can be configured with an indicator, icon, title, and/or header.
11930 * MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar
11931 * is set up. Note that all tools must define an {@link OO.ui.Tool#onUpdateState onUpdateState} method if
11932 * a MenuToolGroup is used.
11935 * // Example of a MenuToolGroup
11936 * var toolFactory = new OO.ui.ToolFactory();
11937 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11938 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11940 * // We will be placing status text in this element when tools are used
11941 * var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the dropdown menu.' );
11943 * // Define the tools that we're going to place in our toolbar
11945 * function SettingsTool() {
11946 * SettingsTool.parent.apply( this, arguments );
11947 * this.reallyActive = false;
11949 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11950 * SettingsTool.static.name = 'settings';
11951 * SettingsTool.static.icon = 'settings';
11952 * SettingsTool.static.title = 'Change settings';
11953 * SettingsTool.prototype.onSelect = function () {
11954 * $area.text( 'Settings tool clicked!' );
11955 * // Toggle the active state on each click
11956 * this.reallyActive = !this.reallyActive;
11957 * this.setActive( this.reallyActive );
11958 * // To update the menu label
11959 * this.toolbar.emit( 'updateState' );
11961 * SettingsTool.prototype.onUpdateState = function () {
11963 * toolFactory.register( SettingsTool );
11965 * function StuffTool() {
11966 * StuffTool.parent.apply( this, arguments );
11967 * this.reallyActive = false;
11969 * OO.inheritClass( StuffTool, OO.ui.Tool );
11970 * StuffTool.static.name = 'stuff';
11971 * StuffTool.static.icon = 'ellipsis';
11972 * StuffTool.static.title = 'More stuff';
11973 * StuffTool.prototype.onSelect = function () {
11974 * $area.text( 'More stuff tool clicked!' );
11975 * // Toggle the active state on each click
11976 * this.reallyActive = !this.reallyActive;
11977 * this.setActive( this.reallyActive );
11978 * // To update the menu label
11979 * this.toolbar.emit( 'updateState' );
11981 * StuffTool.prototype.onUpdateState = function () {
11983 * toolFactory.register( StuffTool );
11985 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11986 * // used once (but not all defined tools must be used).
11990 * header: 'This is the (optional) header',
11991 * title: 'This is the (optional) title',
11992 * indicator: 'down',
11993 * include: [ 'settings', 'stuff' ]
11997 * // Create some UI around the toolbar and place it in the document
11998 * var frame = new OO.ui.PanelLayout( {
12002 * var contentFrame = new OO.ui.PanelLayout( {
12006 * frame.$element.append(
12007 * toolbar.$element,
12008 * contentFrame.$element.append( $area )
12010 * $( 'body' ).append( frame.$element );
12012 * // Here is where the toolbar is actually built. This must be done after inserting it into the
12014 * toolbar.initialize();
12015 * toolbar.emit( 'updateState' );
12017 * For more information about how to add tools to a MenuToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
12018 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki] [1].
12020 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
12023 * @extends OO.ui.PopupToolGroup
12026 * @param {OO.ui.Toolbar} toolbar
12027 * @param {Object} [config] Configuration options
12029 OO
.ui
.MenuToolGroup
= function OoUiMenuToolGroup( toolbar
, config
) {
12030 // Allow passing positional parameters inside the config object
12031 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
12033 toolbar
= config
.toolbar
;
12036 // Configuration initialization
12037 config
= config
|| {};
12039 // Parent constructor
12040 OO
.ui
.MenuToolGroup
.parent
.call( this, toolbar
, config
);
12043 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
12046 this.$element
.addClass( 'oo-ui-menuToolGroup' );
12051 OO
.inheritClass( OO
.ui
.MenuToolGroup
, OO
.ui
.PopupToolGroup
);
12053 /* Static Properties */
12055 OO
.ui
.MenuToolGroup
.static.name
= 'menu';
12060 * Handle the toolbar state being updated.
12062 * When the state changes, the title of each active item in the menu will be joined together and
12063 * used as a label for the group. The label will be empty if none of the items are active.
12067 OO
.ui
.MenuToolGroup
.prototype.onUpdateState = function () {
12071 for ( name
in this.tools
) {
12072 if ( this.tools
[ name
].isActive() ) {
12073 labelTexts
.push( this.tools
[ name
].getTitle() );
12077 this.setLabel( labelTexts
.join( ', ' ) || ' ' );
12081 * Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. Each popup tool is configured
12082 * 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
12083 * an #onSelect or #onUpdateState method, as these methods have been implemented already.
12085 * // Example of a popup tool. When selected, a popup tool displays
12086 * // a popup window.
12087 * function HelpTool( toolGroup, config ) {
12088 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
12093 * this.popup.$body.append( '<p>I am helpful!</p>' );
12095 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
12096 * HelpTool.static.name = 'help';
12097 * HelpTool.static.icon = 'help';
12098 * HelpTool.static.title = 'Help';
12099 * toolFactory.register( HelpTool );
12101 * For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. For more information about
12102 * toolbars in genreral, please see the [OOjs UI documentation on MediaWiki][1].
12104 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
12108 * @extends OO.ui.Tool
12109 * @mixins OO.ui.mixin.PopupElement
12112 * @param {OO.ui.ToolGroup} toolGroup
12113 * @param {Object} [config] Configuration options
12115 OO
.ui
.PopupTool
= function OoUiPopupTool( toolGroup
, config
) {
12116 // Allow passing positional parameters inside the config object
12117 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
12118 config
= toolGroup
;
12119 toolGroup
= config
.toolGroup
;
12122 // Parent constructor
12123 OO
.ui
.PopupTool
.parent
.call( this, toolGroup
, config
);
12125 // Mixin constructors
12126 OO
.ui
.mixin
.PopupElement
.call( this, config
);
12130 .addClass( 'oo-ui-popupTool' )
12131 .append( this.popup
.$element
);
12136 OO
.inheritClass( OO
.ui
.PopupTool
, OO
.ui
.Tool
);
12137 OO
.mixinClass( OO
.ui
.PopupTool
, OO
.ui
.mixin
.PopupElement
);
12142 * Handle the tool being selected.
12146 OO
.ui
.PopupTool
.prototype.onSelect = function () {
12147 if ( !this.isDisabled() ) {
12148 this.popup
.toggle();
12150 this.setActive( false );
12155 * Handle the toolbar state being updated.
12159 OO
.ui
.PopupTool
.prototype.onUpdateState = function () {
12160 this.setActive( false );
12164 * A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools}
12165 * and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used
12166 * inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from
12167 * the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list}
12168 * when the ToolGroupTool is selected.
12170 * // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', defined elsewhere.
12172 * function SettingsTool() {
12173 * SettingsTool.parent.apply( this, arguments );
12175 * OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool );
12176 * SettingsTool.static.name = 'settings';
12177 * SettingsTool.static.title = 'Change settings';
12178 * SettingsTool.static.groupConfig = {
12179 * icon: 'settings',
12180 * label: 'ToolGroupTool',
12181 * include: [ 'setting1', 'setting2' ]
12183 * toolFactory.register( SettingsTool );
12185 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
12187 * Please note that this implementation is subject to change per [T74159] [2].
12189 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars#ToolGroupTool
12190 * [2]: https://phabricator.wikimedia.org/T74159
12194 * @extends OO.ui.Tool
12197 * @param {OO.ui.ToolGroup} toolGroup
12198 * @param {Object} [config] Configuration options
12200 OO
.ui
.ToolGroupTool
= function OoUiToolGroupTool( toolGroup
, config
) {
12201 // Allow passing positional parameters inside the config object
12202 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
12203 config
= toolGroup
;
12204 toolGroup
= config
.toolGroup
;
12207 // Parent constructor
12208 OO
.ui
.ToolGroupTool
.parent
.call( this, toolGroup
, config
);
12211 this.innerToolGroup
= this.createGroup( this.constructor.static.groupConfig
);
12214 this.innerToolGroup
.connect( this, { disable
: 'onToolGroupDisable' } );
12217 this.$link
.remove();
12219 .addClass( 'oo-ui-toolGroupTool' )
12220 .append( this.innerToolGroup
.$element
);
12225 OO
.inheritClass( OO
.ui
.ToolGroupTool
, OO
.ui
.Tool
);
12227 /* Static Properties */
12230 * Toolgroup configuration.
12232 * The toolgroup configuration consists of the tools to include, as well as an icon and label
12233 * to use for the bar item. Tools can be included by symbolic name, group, or with the
12234 * wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information.
12236 * @property {Object.<string,Array>}
12238 OO
.ui
.ToolGroupTool
.static.groupConfig
= {};
12243 * Handle the tool being selected.
12247 OO
.ui
.ToolGroupTool
.prototype.onSelect = function () {
12248 this.innerToolGroup
.setActive( !this.innerToolGroup
.active
);
12253 * Synchronize disabledness state of the tool with the inner toolgroup.
12256 * @param {boolean} disabled Element is disabled
12258 OO
.ui
.ToolGroupTool
.prototype.onToolGroupDisable = function ( disabled
) {
12259 this.setDisabled( disabled
);
12263 * Handle the toolbar state being updated.
12267 OO
.ui
.ToolGroupTool
.prototype.onUpdateState = function () {
12268 this.setActive( false );
12272 * Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration.
12274 * @param {Object.<string,Array>} group Toolgroup configuration. Please see {@link OO.ui.ToolGroup toolgroup} for
12275 * more information.
12276 * @return {OO.ui.ListToolGroup}
12278 OO
.ui
.ToolGroupTool
.prototype.createGroup = function ( group
) {
12279 if ( group
.include
=== '*' ) {
12280 // Apply defaults to catch-all groups
12281 if ( group
.label
=== undefined ) {
12282 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
12286 return this.toolbar
.getToolGroupFactory().create( 'list', this.toolbar
, group
);
12290 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
12292 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
12297 * @extends OO.ui.mixin.GroupElement
12300 * @param {Object} [config] Configuration options
12302 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
12303 // Parent constructor
12304 OO
.ui
.mixin
.GroupWidget
.parent
.call( this, config
);
12309 OO
.inheritClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
12314 * Set the disabled state of the widget.
12316 * This will also update the disabled state of child widgets.
12318 * @param {boolean} disabled Disable widget
12321 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
12325 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
12326 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
12328 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
12329 if ( this.items
) {
12330 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
12331 this.items
[ i
].updateDisabled();
12339 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
12341 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
12342 * allows bidirectional communication.
12344 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
12352 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
12359 * Check if widget is disabled.
12361 * Checks parent if present, making disabled state inheritable.
12363 * @return {boolean} Widget is disabled
12365 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
12366 return this.disabled
||
12367 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
12371 * Set group element is in.
12373 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
12376 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
12378 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
12379 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
12381 // Initialize item disabled states
12382 this.updateDisabled();
12388 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
12389 * Controls include moving items up and down, removing items, and adding different kinds of items.
12391 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
12394 * @extends OO.ui.Widget
12395 * @mixins OO.ui.mixin.GroupElement
12396 * @mixins OO.ui.mixin.IconElement
12399 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
12400 * @param {Object} [config] Configuration options
12401 * @cfg {Object} [abilities] List of abilties
12402 * @cfg {boolean} [abilities.move=true] Allow moving movable items
12403 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
12405 OO
.ui
.OutlineControlsWidget
= function OoUiOutlineControlsWidget( outline
, config
) {
12406 // Allow passing positional parameters inside the config object
12407 if ( OO
.isPlainObject( outline
) && config
=== undefined ) {
12409 outline
= config
.outline
;
12412 // Configuration initialization
12413 config
= $.extend( { icon
: 'add' }, config
);
12415 // Parent constructor
12416 OO
.ui
.OutlineControlsWidget
.parent
.call( this, config
);
12418 // Mixin constructors
12419 OO
.ui
.mixin
.GroupElement
.call( this, config
);
12420 OO
.ui
.mixin
.IconElement
.call( this, config
);
12423 this.outline
= outline
;
12424 this.$movers
= $( '<div>' );
12425 this.upButton
= new OO
.ui
.ButtonWidget( {
12428 title
: OO
.ui
.msg( 'ooui-outline-control-move-up' )
12430 this.downButton
= new OO
.ui
.ButtonWidget( {
12433 title
: OO
.ui
.msg( 'ooui-outline-control-move-down' )
12435 this.removeButton
= new OO
.ui
.ButtonWidget( {
12438 title
: OO
.ui
.msg( 'ooui-outline-control-remove' )
12440 this.abilities
= { move: true, remove
: true };
12443 outline
.connect( this, {
12444 select
: 'onOutlineChange',
12445 add
: 'onOutlineChange',
12446 remove
: 'onOutlineChange'
12448 this.upButton
.connect( this, { click
: [ 'emit', 'move', -1 ] } );
12449 this.downButton
.connect( this, { click
: [ 'emit', 'move', 1 ] } );
12450 this.removeButton
.connect( this, { click
: [ 'emit', 'remove' ] } );
12453 this.$element
.addClass( 'oo-ui-outlineControlsWidget' );
12454 this.$group
.addClass( 'oo-ui-outlineControlsWidget-items' );
12456 .addClass( 'oo-ui-outlineControlsWidget-movers' )
12457 .append( this.removeButton
.$element
, this.upButton
.$element
, this.downButton
.$element
);
12458 this.$element
.append( this.$icon
, this.$group
, this.$movers
);
12459 this.setAbilities( config
.abilities
|| {} );
12464 OO
.inheritClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.Widget
);
12465 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.mixin
.GroupElement
);
12466 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.mixin
.IconElement
);
12472 * @param {number} places Number of places to move
12484 * @param {Object} abilities List of abilties
12485 * @param {boolean} [abilities.move] Allow moving movable items
12486 * @param {boolean} [abilities.remove] Allow removing removable items
12488 OO
.ui
.OutlineControlsWidget
.prototype.setAbilities = function ( abilities
) {
12491 for ( ability
in this.abilities
) {
12492 if ( abilities
[ ability
] !== undefined ) {
12493 this.abilities
[ ability
] = !!abilities
[ ability
];
12497 this.onOutlineChange();
12502 * Handle outline change events.
12504 OO
.ui
.OutlineControlsWidget
.prototype.onOutlineChange = function () {
12505 var i
, len
, firstMovable
, lastMovable
,
12506 items
= this.outline
.getItems(),
12507 selectedItem
= this.outline
.getSelectedItem(),
12508 movable
= this.abilities
.move && selectedItem
&& selectedItem
.isMovable(),
12509 removable
= this.abilities
.remove
&& selectedItem
&& selectedItem
.isRemovable();
12513 len
= items
.length
;
12514 while ( ++i
< len
) {
12515 if ( items
[ i
].isMovable() ) {
12516 firstMovable
= items
[ i
];
12522 if ( items
[ i
].isMovable() ) {
12523 lastMovable
= items
[ i
];
12528 this.upButton
.setDisabled( !movable
|| selectedItem
=== firstMovable
);
12529 this.downButton
.setDisabled( !movable
|| selectedItem
=== lastMovable
);
12530 this.removeButton
.setDisabled( !removable
);
12534 * ToggleWidget implements basic behavior of widgets with an on/off state.
12535 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
12539 * @extends OO.ui.Widget
12542 * @param {Object} [config] Configuration options
12543 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
12544 * By default, the toggle is in the 'off' state.
12546 OO
.ui
.ToggleWidget
= function OoUiToggleWidget( config
) {
12547 // Configuration initialization
12548 config
= config
|| {};
12550 // Parent constructor
12551 OO
.ui
.ToggleWidget
.parent
.call( this, config
);
12557 this.$element
.addClass( 'oo-ui-toggleWidget' );
12558 this.setValue( !!config
.value
);
12563 OO
.inheritClass( OO
.ui
.ToggleWidget
, OO
.ui
.Widget
);
12570 * A change event is emitted when the on/off state of the toggle changes.
12572 * @param {boolean} value Value representing the new state of the toggle
12578 * Get the value representing the toggle’s state.
12580 * @return {boolean} The on/off state of the toggle
12582 OO
.ui
.ToggleWidget
.prototype.getValue = function () {
12587 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
12589 * @param {boolean} value The state of the toggle
12593 OO
.ui
.ToggleWidget
.prototype.setValue = function ( value
) {
12595 if ( this.value
!== value
) {
12596 this.value
= value
;
12597 this.emit( 'change', value
);
12598 this.$element
.toggleClass( 'oo-ui-toggleWidget-on', value
);
12599 this.$element
.toggleClass( 'oo-ui-toggleWidget-off', !value
);
12600 this.$element
.attr( 'aria-checked', value
.toString() );
12606 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
12607 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
12608 * removed, and cleared from the group.
12611 * // Example: A ButtonGroupWidget with two buttons
12612 * var button1 = new OO.ui.PopupButtonWidget( {
12613 * label: 'Select a category',
12616 * $content: $( '<p>List of categories...</p>' ),
12621 * var button2 = new OO.ui.ButtonWidget( {
12622 * label: 'Add item'
12624 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
12625 * items: [button1, button2]
12627 * $( 'body' ).append( buttonGroup.$element );
12630 * @extends OO.ui.Widget
12631 * @mixins OO.ui.mixin.GroupElement
12634 * @param {Object} [config] Configuration options
12635 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
12637 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
12638 // Configuration initialization
12639 config
= config
|| {};
12641 // Parent constructor
12642 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
12644 // Mixin constructors
12645 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
12648 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
12649 if ( Array
.isArray( config
.items
) ) {
12650 this.addItems( config
.items
);
12656 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
12657 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
12660 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
12661 * feels, and functionality can be customized via the class’s configuration options
12662 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12665 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
12668 * // A button widget
12669 * var button = new OO.ui.ButtonWidget( {
12670 * label: 'Button with Icon',
12672 * iconTitle: 'Remove'
12674 * $( 'body' ).append( button.$element );
12676 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
12679 * @extends OO.ui.Widget
12680 * @mixins OO.ui.mixin.ButtonElement
12681 * @mixins OO.ui.mixin.IconElement
12682 * @mixins OO.ui.mixin.IndicatorElement
12683 * @mixins OO.ui.mixin.LabelElement
12684 * @mixins OO.ui.mixin.TitledElement
12685 * @mixins OO.ui.mixin.FlaggedElement
12686 * @mixins OO.ui.mixin.TabIndexedElement
12687 * @mixins OO.ui.mixin.AccessKeyedElement
12690 * @param {Object} [config] Configuration options
12691 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
12692 * @cfg {string} [target] The frame or window in which to open the hyperlink.
12693 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
12695 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
12696 // Configuration initialization
12697 config
= config
|| {};
12699 // Parent constructor
12700 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
12702 // Mixin constructors
12703 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
12704 OO
.ui
.mixin
.IconElement
.call( this, config
);
12705 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
12706 OO
.ui
.mixin
.LabelElement
.call( this, config
);
12707 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
12708 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
12709 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
12710 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$button
} ) );
12714 this.target
= null;
12715 this.noFollow
= false;
12718 this.connect( this, { disable
: 'onDisable' } );
12721 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
12723 .addClass( 'oo-ui-buttonWidget' )
12724 .append( this.$button
);
12725 this.setHref( config
.href
);
12726 this.setTarget( config
.target
);
12727 this.setNoFollow( config
.noFollow
);
12732 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
12733 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
12734 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
12735 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
12736 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
12737 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
12738 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
12739 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
12740 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
12747 OO
.ui
.ButtonWidget
.prototype.onMouseDown = function ( e
) {
12748 if ( !this.isDisabled() ) {
12749 // Remove the tab-index while the button is down to prevent the button from stealing focus
12750 this.$button
.removeAttr( 'tabindex' );
12753 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown
.call( this, e
);
12759 OO
.ui
.ButtonWidget
.prototype.onMouseUp = function ( e
) {
12760 if ( !this.isDisabled() ) {
12761 // Restore the tab-index after the button is up to restore the button's accessibility
12762 this.$button
.attr( 'tabindex', this.tabIndex
);
12765 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp
.call( this, e
);
12769 * Get hyperlink location.
12771 * @return {string} Hyperlink location
12773 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
12778 * Get hyperlink target.
12780 * @return {string} Hyperlink target
12782 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
12783 return this.target
;
12787 * Get search engine traversal hint.
12789 * @return {boolean} Whether search engines should avoid traversing this hyperlink
12791 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
12792 return this.noFollow
;
12796 * Set hyperlink location.
12798 * @param {string|null} href Hyperlink location, null to remove
12800 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
12801 href
= typeof href
=== 'string' ? href
: null;
12802 if ( href
!== null ) {
12803 if ( !OO
.ui
.isSafeUrl( href
) ) {
12804 throw new Error( 'Potentially unsafe href provided: ' + href
);
12809 if ( href
!== this.href
) {
12818 * Update the `href` attribute, in case of changes to href or
12824 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
12825 if ( this.href
!== null && !this.isDisabled() ) {
12826 this.$button
.attr( 'href', this.href
);
12828 this.$button
.removeAttr( 'href' );
12835 * Handle disable events.
12838 * @param {boolean} disabled Element is disabled
12840 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
12845 * Set hyperlink target.
12847 * @param {string|null} target Hyperlink target, null to remove
12849 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
12850 target
= typeof target
=== 'string' ? target
: null;
12852 if ( target
!== this.target
) {
12853 this.target
= target
;
12854 if ( target
!== null ) {
12855 this.$button
.attr( 'target', target
);
12857 this.$button
.removeAttr( 'target' );
12865 * Set search engine traversal hint.
12867 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
12869 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
12870 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
12872 if ( noFollow
!== this.noFollow
) {
12873 this.noFollow
= noFollow
;
12875 this.$button
.attr( 'rel', 'nofollow' );
12877 this.$button
.removeAttr( 'rel' );
12885 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
12886 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
12889 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
12890 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12893 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
12896 * @extends OO.ui.ButtonWidget
12897 * @mixins OO.ui.mixin.PendingElement
12900 * @param {Object} [config] Configuration options
12901 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12902 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
12903 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
12904 * for more information about setting modes.
12905 * @cfg {boolean} [framed=false] Render the action button with a frame
12907 OO
.ui
.ActionWidget
= function OoUiActionWidget( config
) {
12908 // Configuration initialization
12909 config
= $.extend( { framed
: false }, config
);
12911 // Parent constructor
12912 OO
.ui
.ActionWidget
.parent
.call( this, config
);
12914 // Mixin constructors
12915 OO
.ui
.mixin
.PendingElement
.call( this, config
);
12918 this.action
= config
.action
|| '';
12919 this.modes
= config
.modes
|| [];
12924 this.$element
.addClass( 'oo-ui-actionWidget' );
12929 OO
.inheritClass( OO
.ui
.ActionWidget
, OO
.ui
.ButtonWidget
);
12930 OO
.mixinClass( OO
.ui
.ActionWidget
, OO
.ui
.mixin
.PendingElement
);
12935 * A resize event is emitted when the size of the widget changes.
12943 * Check if the action is configured to be available in the specified `mode`.
12945 * @param {string} mode Name of mode
12946 * @return {boolean} The action is configured with the mode
12948 OO
.ui
.ActionWidget
.prototype.hasMode = function ( mode
) {
12949 return this.modes
.indexOf( mode
) !== -1;
12953 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12957 OO
.ui
.ActionWidget
.prototype.getAction = function () {
12958 return this.action
;
12962 * Get the symbolic name of the mode or modes for which the action is configured to be available.
12964 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
12965 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
12968 * @return {string[]}
12970 OO
.ui
.ActionWidget
.prototype.getModes = function () {
12971 return this.modes
.slice();
12975 * Emit a resize event if the size has changed.
12980 OO
.ui
.ActionWidget
.prototype.propagateResize = function () {
12983 if ( this.isElementAttached() ) {
12984 width
= this.$element
.width();
12985 height
= this.$element
.height();
12987 if ( width
!== this.width
|| height
!== this.height
) {
12988 this.width
= width
;
12989 this.height
= height
;
12990 this.emit( 'resize' );
13000 OO
.ui
.ActionWidget
.prototype.setIcon = function () {
13002 OO
.ui
.mixin
.IconElement
.prototype.setIcon
.apply( this, arguments
);
13003 this.propagateResize();
13011 OO
.ui
.ActionWidget
.prototype.setLabel = function () {
13013 OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.apply( this, arguments
);
13014 this.propagateResize();
13022 OO
.ui
.ActionWidget
.prototype.setFlags = function () {
13024 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags
.apply( this, arguments
);
13025 this.propagateResize();
13033 OO
.ui
.ActionWidget
.prototype.clearFlags = function () {
13035 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags
.apply( this, arguments
);
13036 this.propagateResize();
13042 * Toggle the visibility of the action button.
13044 * @param {boolean} [show] Show button, omit to toggle visibility
13047 OO
.ui
.ActionWidget
.prototype.toggle = function () {
13049 OO
.ui
.ActionWidget
.parent
.prototype.toggle
.apply( this, arguments
);
13050 this.propagateResize();
13056 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
13057 * which is used to display additional information or options.
13060 * // Example of a popup button.
13061 * var popupButton = new OO.ui.PopupButtonWidget( {
13062 * label: 'Popup button with options',
13065 * $content: $( '<p>Additional options here.</p>' ),
13067 * align: 'force-left'
13070 * // Append the button to the DOM.
13071 * $( 'body' ).append( popupButton.$element );
13074 * @extends OO.ui.ButtonWidget
13075 * @mixins OO.ui.mixin.PopupElement
13078 * @param {Object} [config] Configuration options
13080 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
13081 // Parent constructor
13082 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
13084 // Mixin constructors
13085 OO
.ui
.mixin
.PopupElement
.call( this, config
);
13088 this.connect( this, { click
: 'onAction' } );
13092 .addClass( 'oo-ui-popupButtonWidget' )
13093 .attr( 'aria-haspopup', 'true' )
13094 .append( this.popup
.$element
);
13099 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
13100 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
13105 * Handle the button action being triggered.
13109 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
13110 this.popup
.toggle();
13114 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
13115 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
13116 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
13117 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
13118 * and {@link OO.ui.mixin.LabelElement labels}. Please see
13119 * the [OOjs UI documentation][1] on MediaWiki for more information.
13122 * // Toggle buttons in the 'off' and 'on' state.
13123 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
13124 * label: 'Toggle Button off'
13126 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
13127 * label: 'Toggle Button on',
13130 * // Append the buttons to the DOM.
13131 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
13133 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
13136 * @extends OO.ui.ToggleWidget
13137 * @mixins OO.ui.mixin.ButtonElement
13138 * @mixins OO.ui.mixin.IconElement
13139 * @mixins OO.ui.mixin.IndicatorElement
13140 * @mixins OO.ui.mixin.LabelElement
13141 * @mixins OO.ui.mixin.TitledElement
13142 * @mixins OO.ui.mixin.FlaggedElement
13143 * @mixins OO.ui.mixin.TabIndexedElement
13146 * @param {Object} [config] Configuration options
13147 * @cfg {boolean} [value=false] The toggle button’s initial on/off
13148 * state. By default, the button is in the 'off' state.
13150 OO
.ui
.ToggleButtonWidget
= function OoUiToggleButtonWidget( config
) {
13151 // Configuration initialization
13152 config
= config
|| {};
13154 // Parent constructor
13155 OO
.ui
.ToggleButtonWidget
.parent
.call( this, config
);
13157 // Mixin constructors
13158 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
13159 OO
.ui
.mixin
.IconElement
.call( this, config
);
13160 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
13161 OO
.ui
.mixin
.LabelElement
.call( this, config
);
13162 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
13163 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
13164 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
13167 this.connect( this, { click
: 'onAction' } );
13170 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
13172 .addClass( 'oo-ui-toggleButtonWidget' )
13173 .append( this.$button
);
13178 OO
.inheritClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.ToggleWidget
);
13179 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
13180 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.IconElement
);
13181 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
13182 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.LabelElement
);
13183 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.TitledElement
);
13184 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
13185 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13190 * Handle the button action being triggered.
13194 OO
.ui
.ToggleButtonWidget
.prototype.onAction = function () {
13195 this.setValue( !this.value
);
13201 OO
.ui
.ToggleButtonWidget
.prototype.setValue = function ( value
) {
13203 if ( value
!== this.value
) {
13204 // Might be called from parent constructor before ButtonElement constructor
13205 if ( this.$button
) {
13206 this.$button
.attr( 'aria-pressed', value
.toString() );
13208 this.setActive( value
);
13212 OO
.ui
.ToggleButtonWidget
.parent
.prototype.setValue
.call( this, value
);
13220 OO
.ui
.ToggleButtonWidget
.prototype.setButtonElement = function ( $button
) {
13221 if ( this.$button
) {
13222 this.$button
.removeAttr( 'aria-pressed' );
13224 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement
.call( this, $button
);
13225 this.$button
.attr( 'aria-pressed', this.value
.toString() );
13229 * CapsuleMultiSelectWidgets are something like a {@link OO.ui.ComboBoxInputWidget combo box widget}
13230 * that allows for selecting multiple values.
13232 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
13235 * // Example: A CapsuleMultiSelectWidget.
13236 * var capsule = new OO.ui.CapsuleMultiSelectWidget( {
13237 * label: 'CapsuleMultiSelectWidget',
13238 * selected: [ 'Option 1', 'Option 3' ],
13241 * new OO.ui.MenuOptionWidget( {
13242 * data: 'Option 1',
13243 * label: 'Option One'
13245 * new OO.ui.MenuOptionWidget( {
13246 * data: 'Option 2',
13247 * label: 'Option Two'
13249 * new OO.ui.MenuOptionWidget( {
13250 * data: 'Option 3',
13251 * label: 'Option Three'
13253 * new OO.ui.MenuOptionWidget( {
13254 * data: 'Option 4',
13255 * label: 'Option Four'
13257 * new OO.ui.MenuOptionWidget( {
13258 * data: 'Option 5',
13259 * label: 'Option Five'
13264 * $( 'body' ).append( capsule.$element );
13266 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13269 * @extends OO.ui.Widget
13270 * @mixins OO.ui.mixin.TabIndexedElement
13271 * @mixins OO.ui.mixin.GroupElement
13274 * @param {Object} [config] Configuration options
13275 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
13276 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
13277 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
13278 * If specified, this popup will be shown instead of the menu (but the menu
13279 * will still be used for item labels and allowArbitrary=false). The widgets
13280 * in the popup should use this.addItemsFromData() or this.addItems() as necessary.
13281 * @cfg {jQuery} [$overlay] Render the menu or popup into a separate layer.
13282 * This configuration is useful in cases where the expanded menu is larger than
13283 * its containing `<div>`. The specified overlay layer is usually on top of
13284 * the containing `<div>` and has a larger area. By default, the menu uses
13285 * relative positioning.
13287 OO
.ui
.CapsuleMultiSelectWidget
= function OoUiCapsuleMultiSelectWidget( config
) {
13290 // Configuration initialization
13291 config
= config
|| {};
13293 // Parent constructor
13294 OO
.ui
.CapsuleMultiSelectWidget
.parent
.call( this, config
);
13296 // Properties (must be set before mixin constructor calls)
13297 this.$input
= config
.popup
? null : $( '<input>' );
13298 this.$handle
= $( '<div>' );
13300 // Mixin constructors
13301 OO
.ui
.mixin
.GroupElement
.call( this, config
);
13302 if ( config
.popup
) {
13303 config
.popup
= $.extend( {}, config
.popup
, {
13307 OO
.ui
.mixin
.PopupElement
.call( this, config
);
13308 $tabFocus
= $( '<span>' );
13309 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: $tabFocus
} ) );
13313 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
13315 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
13316 OO
.ui
.mixin
.IconElement
.call( this, config
);
13319 this.allowArbitrary
= !!config
.allowArbitrary
;
13320 this.$overlay
= config
.$overlay
|| this.$element
;
13321 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
13324 $input
: this.$input
,
13325 $container
: this.$element
,
13326 filterFromInput
: true,
13327 disabled
: this.isDisabled()
13333 if ( this.popup
) {
13335 focus
: this.onFocusForPopup
.bind( this )
13337 this.popup
.$element
.on( 'focusout', this.onPopupFocusOut
.bind( this ) );
13338 if ( this.popup
.$autoCloseIgnore
) {
13339 this.popup
.$autoCloseIgnore
.on( 'focusout', this.onPopupFocusOut
.bind( this ) );
13341 this.popup
.connect( this, {
13342 toggle: function ( visible
) {
13343 $tabFocus
.toggle( !visible
);
13348 focus
: this.onInputFocus
.bind( this ),
13349 blur
: this.onInputBlur
.bind( this ),
13350 'propertychange change click mouseup keydown keyup input cut paste select': this.onInputChange
.bind( this ),
13351 keydown
: this.onKeyDown
.bind( this ),
13352 keypress
: this.onKeyPress
.bind( this )
13355 this.menu
.connect( this, {
13356 choose
: 'onMenuChoose',
13357 add
: 'onMenuItemsChange',
13358 remove
: 'onMenuItemsChange'
13361 click
: this.onClick
.bind( this )
13365 if ( this.$input
) {
13366 this.$input
.prop( 'disabled', this.isDisabled() );
13367 this.$input
.attr( {
13369 'aria-autocomplete': 'list'
13371 this.$input
.width( '1em' );
13373 if ( config
.data
) {
13374 this.setItemsFromData( config
.data
);
13376 this.$group
.addClass( 'oo-ui-capsuleMultiSelectWidget-group' );
13377 this.$handle
.addClass( 'oo-ui-capsuleMultiSelectWidget-handle' )
13378 .append( this.$indicator
, this.$icon
, this.$group
);
13379 this.$element
.addClass( 'oo-ui-capsuleMultiSelectWidget' )
13380 .append( this.$handle
);
13381 if ( this.popup
) {
13382 this.$handle
.append( $tabFocus
);
13383 this.$overlay
.append( this.popup
.$element
);
13385 this.$handle
.append( this.$input
);
13386 this.$overlay
.append( this.menu
.$element
);
13388 this.onMenuItemsChange();
13393 OO
.inheritClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.Widget
);
13394 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.GroupElement
);
13395 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.PopupElement
);
13396 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13397 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.IndicatorElement
);
13398 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.IconElement
);
13405 * A change event is emitted when the set of selected items changes.
13407 * @param {Mixed[]} datas Data of the now-selected items
13413 * Construct a OO.ui.CapsuleItemWidget (or a subclass thereof) from given label and data.
13416 * @param {Mixed} data Custom data of any type.
13417 * @param {string} label The label text.
13418 * @return {OO.ui.CapsuleItemWidget}
13420 OO
.ui
.CapsuleMultiSelectWidget
.prototype.createItemWidget = function ( data
, label
) {
13421 return new OO
.ui
.CapsuleItemWidget( { data
: data
, label
: label
} );
13425 * Get the data of the items in the capsule
13426 * @return {Mixed[]}
13428 OO
.ui
.CapsuleMultiSelectWidget
.prototype.getItemsData = function () {
13429 return $.map( this.getItems(), function ( e
) { return e
.data
; } );
13433 * Set the items in the capsule by providing data
13435 * @param {Mixed[]} datas
13436 * @return {OO.ui.CapsuleMultiSelectWidget}
13438 OO
.ui
.CapsuleMultiSelectWidget
.prototype.setItemsFromData = function ( datas
) {
13441 items
= this.getItems();
13443 $.each( datas
, function ( i
, data
) {
13445 item
= menu
.getItemFromData( data
);
13448 label
= item
.label
;
13449 } else if ( widget
.allowArbitrary
) {
13450 label
= String( data
);
13456 for ( j
= 0; j
< items
.length
; j
++ ) {
13457 if ( items
[ j
].data
=== data
&& items
[ j
].label
=== label
) {
13459 items
.splice( j
, 1 );
13464 item
= widget
.createItemWidget( data
, label
);
13466 widget
.addItems( [ item
], i
);
13469 if ( items
.length
) {
13470 widget
.removeItems( items
);
13477 * Add items to the capsule by providing their data
13479 * @param {Mixed[]} datas
13480 * @return {OO.ui.CapsuleMultiSelectWidget}
13482 OO
.ui
.CapsuleMultiSelectWidget
.prototype.addItemsFromData = function ( datas
) {
13487 $.each( datas
, function ( i
, data
) {
13490 if ( !widget
.getItemFromData( data
) ) {
13491 item
= menu
.getItemFromData( data
);
13493 items
.push( widget
.createItemWidget( data
, item
.label
) );
13494 } else if ( widget
.allowArbitrary
) {
13495 items
.push( widget
.createItemWidget( data
, String( data
) ) );
13500 if ( items
.length
) {
13501 this.addItems( items
);
13508 * Remove items by data
13510 * @param {Mixed[]} datas
13511 * @return {OO.ui.CapsuleMultiSelectWidget}
13513 OO
.ui
.CapsuleMultiSelectWidget
.prototype.removeItemsFromData = function ( datas
) {
13517 $.each( datas
, function ( i
, data
) {
13518 var item
= widget
.getItemFromData( data
);
13520 items
.push( item
);
13524 if ( items
.length
) {
13525 this.removeItems( items
);
13534 OO
.ui
.CapsuleMultiSelectWidget
.prototype.addItems = function ( items
) {
13536 oldItems
= this.items
.slice();
13538 OO
.ui
.mixin
.GroupElement
.prototype.addItems
.call( this, items
);
13540 if ( this.items
.length
!== oldItems
.length
) {
13544 for ( i
= 0, l
= oldItems
.length
; same
&& i
< l
; i
++ ) {
13545 same
= same
&& this.items
[ i
] === oldItems
[ i
];
13549 this.emit( 'change', this.getItemsData() );
13558 OO
.ui
.CapsuleMultiSelectWidget
.prototype.removeItems = function ( items
) {
13560 oldItems
= this.items
.slice();
13562 OO
.ui
.mixin
.GroupElement
.prototype.removeItems
.call( this, items
);
13564 if ( this.items
.length
!== oldItems
.length
) {
13568 for ( i
= 0, l
= oldItems
.length
; same
&& i
< l
; i
++ ) {
13569 same
= same
&& this.items
[ i
] === oldItems
[ i
];
13573 this.emit( 'change', this.getItemsData() );
13582 OO
.ui
.CapsuleMultiSelectWidget
.prototype.clearItems = function () {
13583 if ( this.items
.length
) {
13584 OO
.ui
.mixin
.GroupElement
.prototype.clearItems
.call( this );
13585 this.emit( 'change', this.getItemsData() );
13591 * Get the capsule widget's menu.
13592 * @return {OO.ui.MenuSelectWidget} Menu widget
13594 OO
.ui
.CapsuleMultiSelectWidget
.prototype.getMenu = function () {
13599 * Handle focus events
13602 * @param {jQuery.Event} event
13604 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onInputFocus = function () {
13605 if ( !this.isDisabled() ) {
13606 this.menu
.toggle( true );
13611 * Handle blur events
13614 * @param {jQuery.Event} event
13616 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onInputBlur = function () {
13617 if ( this.allowArbitrary
&& this.$input
.val().trim() !== '' ) {
13618 this.addItemsFromData( [ this.$input
.val() ] );
13624 * Handle focus events
13627 * @param {jQuery.Event} event
13629 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onFocusForPopup = function () {
13630 if ( !this.isDisabled() ) {
13631 this.popup
.setSize( this.$handle
.width() );
13632 this.popup
.toggle( true );
13633 this.popup
.$element
.find( '*' )
13634 .filter( function () { return OO
.ui
.isFocusableElement( $( this ), true ); } )
13641 * Handles popup focus out events.
13644 * @param {Event} e Focus out event
13646 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onPopupFocusOut = function () {
13647 var widget
= this.popup
;
13649 setTimeout( function () {
13651 widget
.isVisible() &&
13652 !OO
.ui
.contains( widget
.$element
[ 0 ], document
.activeElement
, true ) &&
13653 ( !widget
.$autoCloseIgnore
|| !widget
.$autoCloseIgnore
.has( document
.activeElement
).length
)
13655 widget
.toggle( false );
13661 * Handle mouse click events.
13664 * @param {jQuery.Event} e Mouse click event
13666 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onClick = function ( e
) {
13667 if ( e
.which
=== 1 ) {
13674 * Handle key press events.
13677 * @param {jQuery.Event} e Key press event
13679 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onKeyPress = function ( e
) {
13682 if ( !this.isDisabled() ) {
13683 if ( e
.which
=== OO
.ui
.Keys
.ESCAPE
) {
13688 if ( !this.popup
) {
13689 this.menu
.toggle( true );
13690 if ( e
.which
=== OO
.ui
.Keys
.ENTER
) {
13691 item
= this.menu
.getItemFromLabel( this.$input
.val(), true );
13693 this.addItemsFromData( [ item
.data
] );
13695 } else if ( this.allowArbitrary
&& this.$input
.val().trim() !== '' ) {
13696 this.addItemsFromData( [ this.$input
.val() ] );
13702 // Make sure the input gets resized.
13703 setTimeout( this.onInputChange
.bind( this ), 0 );
13709 * Handle key down events.
13712 * @param {jQuery.Event} e Key down event
13714 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onKeyDown = function ( e
) {
13715 if ( !this.isDisabled() ) {
13716 // 'keypress' event is not triggered for Backspace
13717 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.$input
.val() === '' ) {
13718 if ( this.items
.length
) {
13719 this.removeItems( this.items
.slice( -1 ) );
13727 * Handle input change events.
13730 * @param {jQuery.Event} e Event of some sort
13732 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onInputChange = function () {
13733 if ( !this.isDisabled() ) {
13734 this.$input
.width( this.$input
.val().length
+ 'em' );
13739 * Handle menu choose events.
13742 * @param {OO.ui.OptionWidget} item Chosen item
13744 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onMenuChoose = function ( item
) {
13745 if ( item
&& item
.isVisible() ) {
13746 this.addItemsFromData( [ item
.getData() ] );
13752 * Handle menu item change events.
13756 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onMenuItemsChange = function () {
13757 this.setItemsFromData( this.getItemsData() );
13758 this.$element
.toggleClass( 'oo-ui-capsuleMultiSelectWidget-empty', this.menu
.isEmpty() );
13762 * Clear the input field
13765 OO
.ui
.CapsuleMultiSelectWidget
.prototype.clearInput = function () {
13766 if ( this.$input
) {
13767 this.$input
.val( '' );
13768 this.$input
.width( '1em' );
13770 if ( this.popup
) {
13771 this.popup
.toggle( false );
13773 this.menu
.toggle( false );
13774 this.menu
.selectItem();
13775 this.menu
.highlightItem();
13781 OO
.ui
.CapsuleMultiSelectWidget
.prototype.setDisabled = function ( disabled
) {
13785 OO
.ui
.CapsuleMultiSelectWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
13787 if ( this.$input
) {
13788 this.$input
.prop( 'disabled', this.isDisabled() );
13791 this.menu
.setDisabled( this.isDisabled() );
13793 if ( this.popup
) {
13794 this.popup
.setDisabled( this.isDisabled() );
13797 if ( this.items
) {
13798 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
13799 this.items
[ i
].updateDisabled();
13809 * @return {OO.ui.CapsuleMultiSelectWidget}
13811 OO
.ui
.CapsuleMultiSelectWidget
.prototype.focus = function () {
13812 if ( !this.isDisabled() ) {
13813 if ( this.popup
) {
13814 this.popup
.setSize( this.$handle
.width() );
13815 this.popup
.toggle( true );
13816 this.popup
.$element
.find( '*' )
13817 .filter( function () { return OO
.ui
.isFocusableElement( $( this ), true ); } )
13821 this.menu
.toggle( true );
13822 this.$input
.focus();
13829 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiSelectWidget
13830 * CapsuleMultiSelectWidget} to display the selected items.
13833 * @extends OO.ui.Widget
13834 * @mixins OO.ui.mixin.ItemWidget
13835 * @mixins OO.ui.mixin.IndicatorElement
13836 * @mixins OO.ui.mixin.LabelElement
13837 * @mixins OO.ui.mixin.FlaggedElement
13838 * @mixins OO.ui.mixin.TabIndexedElement
13841 * @param {Object} [config] Configuration options
13843 OO
.ui
.CapsuleItemWidget
= function OoUiCapsuleItemWidget( config
) {
13844 // Configuration initialization
13845 config
= config
|| {};
13847 // Parent constructor
13848 OO
.ui
.CapsuleItemWidget
.parent
.call( this, config
);
13850 // Properties (must be set before mixin constructor calls)
13851 this.$indicator
= $( '<span>' );
13853 // Mixin constructors
13854 OO
.ui
.mixin
.ItemWidget
.call( this );
13855 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$indicator
, indicator
: 'clear' } ) );
13856 OO
.ui
.mixin
.LabelElement
.call( this, config
);
13857 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
13858 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$indicator
} ) );
13861 this.$indicator
.on( {
13862 keydown
: this.onCloseKeyDown
.bind( this ),
13863 click
: this.onCloseClick
.bind( this )
13868 .addClass( 'oo-ui-capsuleItemWidget' )
13869 .append( this.$indicator
, this.$label
);
13874 OO
.inheritClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.Widget
);
13875 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.ItemWidget
);
13876 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.IndicatorElement
);
13877 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.LabelElement
);
13878 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.FlaggedElement
);
13879 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13884 * Handle close icon clicks
13885 * @param {jQuery.Event} event
13887 OO
.ui
.CapsuleItemWidget
.prototype.onCloseClick = function () {
13888 var element
= this.getElementGroup();
13890 if ( !this.isDisabled() && element
&& $.isFunction( element
.removeItems
) ) {
13891 element
.removeItems( [ this ] );
13897 * Handle close keyboard events
13898 * @param {jQuery.Event} event Key down event
13900 OO
.ui
.CapsuleItemWidget
.prototype.onCloseKeyDown = function ( e
) {
13901 if ( !this.isDisabled() && $.isFunction( this.getElementGroup().removeItems
) ) {
13902 switch ( e
.which
) {
13903 case OO
.ui
.Keys
.ENTER
:
13904 case OO
.ui
.Keys
.BACKSPACE
:
13905 case OO
.ui
.Keys
.SPACE
:
13906 this.getElementGroup().removeItems( [ this ] );
13913 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
13914 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
13915 * users can interact with it.
13917 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
13918 * OO.ui.DropdownInputWidget instead.
13921 * // Example: A DropdownWidget with a menu that contains three options
13922 * var dropDown = new OO.ui.DropdownWidget( {
13923 * label: 'Dropdown menu: Select a menu option',
13926 * new OO.ui.MenuOptionWidget( {
13930 * new OO.ui.MenuOptionWidget( {
13934 * new OO.ui.MenuOptionWidget( {
13942 * $( 'body' ).append( dropDown.$element );
13944 * dropDown.getMenu().selectItemByData( 'b' );
13946 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
13948 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
13950 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13953 * @extends OO.ui.Widget
13954 * @mixins OO.ui.mixin.IconElement
13955 * @mixins OO.ui.mixin.IndicatorElement
13956 * @mixins OO.ui.mixin.LabelElement
13957 * @mixins OO.ui.mixin.TitledElement
13958 * @mixins OO.ui.mixin.TabIndexedElement
13961 * @param {Object} [config] Configuration options
13962 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
13963 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
13964 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
13965 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
13967 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
13968 // Configuration initialization
13969 config
= $.extend( { indicator
: 'down' }, config
);
13971 // Parent constructor
13972 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
13974 // Properties (must be set before TabIndexedElement constructor call)
13975 this.$handle
= this.$( '<span>' );
13976 this.$overlay
= config
.$overlay
|| this.$element
;
13978 // Mixin constructors
13979 OO
.ui
.mixin
.IconElement
.call( this, config
);
13980 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
13981 OO
.ui
.mixin
.LabelElement
.call( this, config
);
13982 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
13983 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
13986 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend( {
13988 $container
: this.$element
13989 }, config
.menu
) );
13993 click
: this.onClick
.bind( this ),
13994 keypress
: this.onKeyPress
.bind( this )
13996 this.menu
.connect( this, { select
: 'onMenuSelect' } );
14000 .addClass( 'oo-ui-dropdownWidget-handle' )
14001 .append( this.$icon
, this.$label
, this.$indicator
);
14003 .addClass( 'oo-ui-dropdownWidget' )
14004 .append( this.$handle
);
14005 this.$overlay
.append( this.menu
.$element
);
14010 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
14011 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
14012 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
14013 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
14014 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
14015 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
14022 * @return {OO.ui.MenuSelectWidget} Menu of widget
14024 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
14029 * Handles menu select events.
14032 * @param {OO.ui.MenuOptionWidget} item Selected menu item
14034 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
14038 this.setLabel( null );
14042 selectedLabel
= item
.getLabel();
14044 // If the label is a DOM element, clone it, because setLabel will append() it
14045 if ( selectedLabel
instanceof jQuery
) {
14046 selectedLabel
= selectedLabel
.clone();
14049 this.setLabel( selectedLabel
);
14053 * Handle mouse click events.
14056 * @param {jQuery.Event} e Mouse click event
14058 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
14059 if ( !this.isDisabled() && e
.which
=== 1 ) {
14060 this.menu
.toggle();
14066 * Handle key press events.
14069 * @param {jQuery.Event} e Key press event
14071 OO
.ui
.DropdownWidget
.prototype.onKeyPress = function ( e
) {
14072 if ( !this.isDisabled() &&
14073 ( ( e
.which
=== OO
.ui
.Keys
.SPACE
&& !this.menu
.isVisible() ) || e
.which
=== OO
.ui
.Keys
.ENTER
)
14075 this.menu
.toggle();
14081 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
14082 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
14083 * OO.ui.mixin.IndicatorElement indicators}.
14084 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14087 * // Example of a file select widget
14088 * var selectFile = new OO.ui.SelectFileWidget();
14089 * $( 'body' ).append( selectFile.$element );
14091 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
14094 * @extends OO.ui.Widget
14095 * @mixins OO.ui.mixin.IconElement
14096 * @mixins OO.ui.mixin.IndicatorElement
14097 * @mixins OO.ui.mixin.PendingElement
14098 * @mixins OO.ui.mixin.LabelElement
14101 * @param {Object} [config] Configuration options
14102 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
14103 * @cfg {string} [placeholder] Text to display when no file is selected.
14104 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
14105 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
14106 * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
14107 * @cfg {boolean} [dragDropUI=false] Deprecated alias for showDropTarget
14109 OO
.ui
.SelectFileWidget
= function OoUiSelectFileWidget( config
) {
14112 // TODO: Remove in next release
14113 if ( config
&& config
.dragDropUI
) {
14114 config
.showDropTarget
= true;
14117 // Configuration initialization
14118 config
= $.extend( {
14120 placeholder
: OO
.ui
.msg( 'ooui-selectfile-placeholder' ),
14121 notsupported
: OO
.ui
.msg( 'ooui-selectfile-not-supported' ),
14123 showDropTarget
: false
14126 // Parent constructor
14127 OO
.ui
.SelectFileWidget
.parent
.call( this, config
);
14129 // Mixin constructors
14130 OO
.ui
.mixin
.IconElement
.call( this, config
);
14131 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
14132 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$info
} ) );
14133 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { autoFitLabel
: true } ) );
14136 this.$info
= $( '<span>' );
14139 this.showDropTarget
= config
.showDropTarget
;
14140 this.isSupported
= this.constructor.static.isSupported();
14141 this.currentFile
= null;
14142 if ( Array
.isArray( config
.accept
) ) {
14143 this.accept
= config
.accept
;
14145 this.accept
= null;
14147 this.placeholder
= config
.placeholder
;
14148 this.notsupported
= config
.notsupported
;
14149 this.onFileSelectedHandler
= this.onFileSelected
.bind( this );
14151 this.selectButton
= new OO
.ui
.ButtonWidget( {
14152 classes
: [ 'oo-ui-selectFileWidget-selectButton' ],
14153 label
: 'Select a file',
14154 disabled
: this.disabled
|| !this.isSupported
14157 this.clearButton
= new OO
.ui
.ButtonWidget( {
14158 classes
: [ 'oo-ui-selectFileWidget-clearButton' ],
14161 disabled
: this.disabled
14165 this.selectButton
.$button
.on( {
14166 keypress
: this.onKeyPress
.bind( this )
14168 this.clearButton
.connect( this, {
14169 click
: 'onClearClick'
14171 if ( config
.droppable
) {
14172 dragHandler
= this.onDragEnterOrOver
.bind( this );
14173 this.$element
.on( {
14174 dragenter
: dragHandler
,
14175 dragover
: dragHandler
,
14176 dragleave
: this.onDragLeave
.bind( this ),
14177 drop
: this.onDrop
.bind( this )
14184 this.$label
.addClass( 'oo-ui-selectFileWidget-label' );
14186 .addClass( 'oo-ui-selectFileWidget-info' )
14187 .append( this.$icon
, this.$label
, this.clearButton
.$element
, this.$indicator
);
14189 .addClass( 'oo-ui-selectFileWidget' )
14190 .append( this.$info
, this.selectButton
.$element
);
14191 if ( config
.droppable
&& config
.showDropTarget
) {
14192 this.$dropTarget
= $( '<div>' )
14193 .addClass( 'oo-ui-selectFileWidget-dropTarget' )
14194 .text( OO
.ui
.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
14196 click
: this.onDropTargetClick
.bind( this )
14198 this.$element
.prepend( this.$dropTarget
);
14204 OO
.inheritClass( OO
.ui
.SelectFileWidget
, OO
.ui
.Widget
);
14205 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.IconElement
);
14206 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.IndicatorElement
);
14207 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.PendingElement
);
14208 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.LabelElement
);
14210 /* Static Properties */
14213 * Check if this widget is supported
14216 * @return {boolean}
14218 OO
.ui
.SelectFileWidget
.static.isSupported = function () {
14220 if ( OO
.ui
.SelectFileWidget
.static.isSupportedCache
=== null ) {
14221 $input
= $( '<input type="file">' );
14222 OO
.ui
.SelectFileWidget
.static.isSupportedCache
= $input
[ 0 ].files
!== undefined;
14224 return OO
.ui
.SelectFileWidget
.static.isSupportedCache
;
14227 OO
.ui
.SelectFileWidget
.static.isSupportedCache
= null;
14234 * A change event is emitted when the on/off state of the toggle changes.
14236 * @param {File|null} value New value
14242 * Get the current value of the field
14244 * @return {File|null}
14246 OO
.ui
.SelectFileWidget
.prototype.getValue = function () {
14247 return this.currentFile
;
14251 * Set the current value of the field
14253 * @param {File|null} file File to select
14255 OO
.ui
.SelectFileWidget
.prototype.setValue = function ( file
) {
14256 if ( this.currentFile
!== file
) {
14257 this.currentFile
= file
;
14259 this.emit( 'change', this.currentFile
);
14264 * Focus the widget.
14266 * Focusses the select file button.
14270 OO
.ui
.SelectFileWidget
.prototype.focus = function () {
14271 this.selectButton
.$button
[ 0 ].focus();
14276 * Update the user interface when a file is selected or unselected
14280 OO
.ui
.SelectFileWidget
.prototype.updateUI = function () {
14282 if ( !this.isSupported
) {
14283 this.$element
.addClass( 'oo-ui-selectFileWidget-notsupported' );
14284 this.$element
.removeClass( 'oo-ui-selectFileWidget-empty' );
14285 this.setLabel( this.notsupported
);
14287 this.$element
.addClass( 'oo-ui-selectFileWidget-supported' );
14288 if ( this.currentFile
) {
14289 this.$element
.removeClass( 'oo-ui-selectFileWidget-empty' );
14291 if ( this.currentFile
.type
!== '' ) {
14292 $label
= $label
.add( $( '<span>' ).addClass( 'oo-ui-selectFileWidget-fileType' ).text( this.currentFile
.type
) );
14294 $label
= $label
.add( $( '<span>' ).text( this.currentFile
.name
) );
14295 this.setLabel( $label
);
14297 this.$element
.addClass( 'oo-ui-selectFileWidget-empty' );
14298 this.setLabel( this.placeholder
);
14302 if ( this.$input
) {
14303 this.$input
.attr( 'title', this.getLabel() );
14308 * Add the input to the widget
14312 OO
.ui
.SelectFileWidget
.prototype.addInput = function () {
14313 if ( this.$input
) {
14314 this.$input
.remove();
14317 if ( !this.isSupported
) {
14318 this.$input
= null;
14322 this.$input
= $( '<input type="file">' );
14323 this.$input
.on( 'change', this.onFileSelectedHandler
);
14324 this.$input
.attr( {
14326 title
: this.getLabel()
14328 if ( this.accept
) {
14329 this.$input
.attr( 'accept', this.accept
.join( ', ' ) );
14331 this.selectButton
.$button
.append( this.$input
);
14335 * Determine if we should accept this file
14338 * @param {string} File MIME type
14339 * @return {boolean}
14341 OO
.ui
.SelectFileWidget
.prototype.isAllowedType = function ( mimeType
) {
14344 if ( !this.accept
|| !mimeType
) {
14348 for ( i
= 0; i
< this.accept
.length
; i
++ ) {
14349 mimeTest
= this.accept
[ i
];
14350 if ( mimeTest
=== mimeType
) {
14352 } else if ( mimeTest
.substr( -2 ) === '/*' ) {
14353 mimeTest
= mimeTest
.substr( 0, mimeTest
.length
- 1 );
14354 if ( mimeType
.substr( 0, mimeTest
.length
) === mimeTest
) {
14364 * Handle file selection from the input
14367 * @param {jQuery.Event} e
14369 OO
.ui
.SelectFileWidget
.prototype.onFileSelected = function ( e
) {
14370 var file
= OO
.getProp( e
.target
, 'files', 0 ) || null;
14372 if ( file
&& !this.isAllowedType( file
.type
) ) {
14376 this.setValue( file
);
14381 * Handle clear button click events.
14385 OO
.ui
.SelectFileWidget
.prototype.onClearClick = function () {
14386 this.setValue( null );
14391 * Handle key press events.
14394 * @param {jQuery.Event} e Key press event
14396 OO
.ui
.SelectFileWidget
.prototype.onKeyPress = function ( e
) {
14397 if ( this.isSupported
&& !this.isDisabled() && this.$input
&&
14398 ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
14400 this.$input
.click();
14406 * Handle drop target click events.
14409 * @param {jQuery.Event} e Key press event
14411 OO
.ui
.SelectFileWidget
.prototype.onDropTargetClick = function () {
14412 if ( this.isSupported
&& !this.isDisabled() && this.$input
) {
14413 this.$input
.click();
14419 * Handle drag enter and over events
14422 * @param {jQuery.Event} e Drag event
14424 OO
.ui
.SelectFileWidget
.prototype.onDragEnterOrOver = function ( e
) {
14426 droppableFile
= false,
14427 dt
= e
.originalEvent
.dataTransfer
;
14429 e
.preventDefault();
14430 e
.stopPropagation();
14432 if ( this.isDisabled() || !this.isSupported
) {
14433 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14434 dt
.dropEffect
= 'none';
14438 // DataTransferItem and File both have a type property, but in Chrome files
14439 // have no information at this point.
14440 itemOrFile
= OO
.getProp( dt
, 'items', 0 ) || OO
.getProp( dt
, 'files', 0 );
14441 if ( itemOrFile
) {
14442 if ( this.isAllowedType( itemOrFile
.type
) ) {
14443 droppableFile
= true;
14445 // dt.types is Array-like, but not an Array
14446 } else if ( Array
.prototype.indexOf
.call( OO
.getProp( dt
, 'types' ) || [], 'Files' ) !== -1 ) {
14447 // File information is not available at this point for security so just assume
14448 // it is acceptable for now.
14449 // https://bugzilla.mozilla.org/show_bug.cgi?id=640534
14450 droppableFile
= true;
14453 this.$element
.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile
);
14454 if ( !droppableFile
) {
14455 dt
.dropEffect
= 'none';
14462 * Handle drag leave events
14465 * @param {jQuery.Event} e Drag event
14467 OO
.ui
.SelectFileWidget
.prototype.onDragLeave = function () {
14468 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14472 * Handle drop events
14475 * @param {jQuery.Event} e Drop event
14477 OO
.ui
.SelectFileWidget
.prototype.onDrop = function ( e
) {
14479 dt
= e
.originalEvent
.dataTransfer
;
14481 e
.preventDefault();
14482 e
.stopPropagation();
14483 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14485 if ( this.isDisabled() || !this.isSupported
) {
14489 file
= OO
.getProp( dt
, 'files', 0 );
14490 if ( file
&& !this.isAllowedType( file
.type
) ) {
14494 this.setValue( file
);
14503 OO
.ui
.SelectFileWidget
.prototype.setDisabled = function ( disabled
) {
14504 OO
.ui
.SelectFileWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
14505 if ( this.selectButton
) {
14506 this.selectButton
.setDisabled( disabled
);
14508 if ( this.clearButton
) {
14509 this.clearButton
.setDisabled( disabled
);
14515 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
14516 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
14517 * for a list of icons included in the library.
14520 * // An icon widget with a label
14521 * var myIcon = new OO.ui.IconWidget( {
14523 * iconTitle: 'Help'
14525 * // Create a label.
14526 * var iconLabel = new OO.ui.LabelWidget( {
14529 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
14531 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
14534 * @extends OO.ui.Widget
14535 * @mixins OO.ui.mixin.IconElement
14536 * @mixins OO.ui.mixin.TitledElement
14537 * @mixins OO.ui.mixin.FlaggedElement
14540 * @param {Object} [config] Configuration options
14542 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
14543 // Configuration initialization
14544 config
= config
|| {};
14546 // Parent constructor
14547 OO
.ui
.IconWidget
.parent
.call( this, config
);
14549 // Mixin constructors
14550 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
14551 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
14552 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
14555 this.$element
.addClass( 'oo-ui-iconWidget' );
14560 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
14561 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
14562 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
14563 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
14565 /* Static Properties */
14567 OO
.ui
.IconWidget
.static.tagName
= 'span';
14570 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
14571 * attention to the status of an item or to clarify the function of a control. For a list of
14572 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
14575 * // Example of an indicator widget
14576 * var indicator1 = new OO.ui.IndicatorWidget( {
14577 * indicator: 'alert'
14580 * // Create a fieldset layout to add a label
14581 * var fieldset = new OO.ui.FieldsetLayout();
14582 * fieldset.addItems( [
14583 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
14585 * $( 'body' ).append( fieldset.$element );
14587 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
14590 * @extends OO.ui.Widget
14591 * @mixins OO.ui.mixin.IndicatorElement
14592 * @mixins OO.ui.mixin.TitledElement
14595 * @param {Object} [config] Configuration options
14597 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
14598 // Configuration initialization
14599 config
= config
|| {};
14601 // Parent constructor
14602 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
14604 // Mixin constructors
14605 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
14606 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
14609 this.$element
.addClass( 'oo-ui-indicatorWidget' );
14614 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
14615 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
14616 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
14618 /* Static Properties */
14620 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
14623 * InputWidget is the base class for all input widgets, which
14624 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
14625 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
14626 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14628 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14632 * @extends OO.ui.Widget
14633 * @mixins OO.ui.mixin.FlaggedElement
14634 * @mixins OO.ui.mixin.TabIndexedElement
14635 * @mixins OO.ui.mixin.TitledElement
14636 * @mixins OO.ui.mixin.AccessKeyedElement
14639 * @param {Object} [config] Configuration options
14640 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
14641 * @cfg {string} [value=''] The value of the input.
14642 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
14643 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
14644 * before it is accepted.
14646 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
14647 // Configuration initialization
14648 config
= config
|| {};
14650 // Parent constructor
14651 OO
.ui
.InputWidget
.parent
.call( this, config
);
14654 this.$input
= this.getInputElement( config
);
14656 this.inputFilter
= config
.inputFilter
;
14658 // Mixin constructors
14659 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
14660 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
14661 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
14662 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$input
} ) );
14665 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
14669 .addClass( 'oo-ui-inputWidget-input' )
14670 .attr( 'name', config
.name
)
14671 .prop( 'disabled', this.isDisabled() );
14673 .addClass( 'oo-ui-inputWidget' )
14674 .append( this.$input
);
14675 this.setValue( config
.value
);
14676 this.setAccessKey( config
.accessKey
);
14677 if ( config
.dir
) {
14678 this.setDir( config
.dir
);
14684 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
14685 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
14686 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
14687 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
14688 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
14690 /* Static Properties */
14692 OO
.ui
.InputWidget
.static.supportsSimpleLabel
= true;
14694 /* Static Methods */
14699 OO
.ui
.InputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
14700 config
= OO
.ui
.InputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
14701 // Reusing $input lets browsers preserve inputted values across page reloads (T114134)
14702 config
.$input
= $( node
).find( '.oo-ui-inputWidget-input' );
14709 OO
.ui
.InputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
14710 var state
= OO
.ui
.InputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
14711 state
.value
= config
.$input
.val();
14712 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
14713 state
.focus
= config
.$input
.is( ':focus' );
14722 * A change event is emitted when the value of the input changes.
14724 * @param {string} value
14730 * Get input element.
14732 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
14733 * different circumstances. The element must have a `value` property (like form elements).
14736 * @param {Object} config Configuration options
14737 * @return {jQuery} Input element
14739 OO
.ui
.InputWidget
.prototype.getInputElement = function ( config
) {
14740 // See #reusePreInfuseDOM about config.$input
14741 return config
.$input
|| $( '<input>' );
14745 * Handle potentially value-changing events.
14748 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
14750 OO
.ui
.InputWidget
.prototype.onEdit = function () {
14752 if ( !this.isDisabled() ) {
14753 // Allow the stack to clear so the value will be updated
14754 setTimeout( function () {
14755 widget
.setValue( widget
.$input
.val() );
14761 * Get the value of the input.
14763 * @return {string} Input value
14765 OO
.ui
.InputWidget
.prototype.getValue = function () {
14766 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14767 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14768 var value
= this.$input
.val();
14769 if ( this.value
!== value
) {
14770 this.setValue( value
);
14776 * Set the directionality of the input, either RTL (right-to-left) or LTR (left-to-right).
14778 * @deprecated since v0.13.1, use #setDir directly
14779 * @param {boolean} isRTL Directionality is right-to-left
14782 OO
.ui
.InputWidget
.prototype.setRTL = function ( isRTL
) {
14783 this.setDir( isRTL
? 'rtl' : 'ltr' );
14788 * Set the directionality of the input.
14790 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
14793 OO
.ui
.InputWidget
.prototype.setDir = function ( dir
) {
14794 this.$input
.prop( 'dir', dir
);
14799 * Set the value of the input.
14801 * @param {string} value New value
14805 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
14806 value
= this.cleanUpValue( value
);
14807 // Update the DOM if it has changed. Note that with cleanUpValue, it
14808 // is possible for the DOM value to change without this.value changing.
14809 if ( this.$input
.val() !== value
) {
14810 this.$input
.val( value
);
14812 if ( this.value
!== value
) {
14813 this.value
= value
;
14814 this.emit( 'change', this.value
);
14820 * Set the input's access key.
14821 * FIXME: This is the same code as in OO.ui.mixin.ButtonElement, maybe find a better place for it?
14823 * @param {string} accessKey Input's access key, use empty string to remove
14826 OO
.ui
.InputWidget
.prototype.setAccessKey = function ( accessKey
) {
14827 accessKey
= typeof accessKey
=== 'string' && accessKey
.length
? accessKey
: null;
14829 if ( this.accessKey
!== accessKey
) {
14830 if ( this.$input
) {
14831 if ( accessKey
!== null ) {
14832 this.$input
.attr( 'accesskey', accessKey
);
14834 this.$input
.removeAttr( 'accesskey' );
14837 this.accessKey
= accessKey
;
14844 * Clean up incoming value.
14846 * Ensures value is a string, and converts undefined and null to empty string.
14849 * @param {string} value Original value
14850 * @return {string} Cleaned up value
14852 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
14853 if ( value
=== undefined || value
=== null ) {
14855 } else if ( this.inputFilter
) {
14856 return this.inputFilter( String( value
) );
14858 return String( value
);
14863 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
14864 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
14867 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
14868 if ( !this.isDisabled() ) {
14869 if ( this.$input
.is( ':checkbox, :radio' ) ) {
14870 this.$input
.click();
14872 if ( this.$input
.is( ':input' ) ) {
14873 this.$input
[ 0 ].focus();
14881 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
14882 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
14883 if ( this.$input
) {
14884 this.$input
.prop( 'disabled', this.isDisabled() );
14894 OO
.ui
.InputWidget
.prototype.focus = function () {
14895 this.$input
[ 0 ].focus();
14904 OO
.ui
.InputWidget
.prototype.blur = function () {
14905 this.$input
[ 0 ].blur();
14912 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
14913 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
14914 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
14915 this.setValue( state
.value
);
14917 if ( state
.focus
) {
14923 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
14924 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
14925 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
14926 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
14927 * [OOjs UI documentation on MediaWiki] [1] for more information.
14930 * // A ButtonInputWidget rendered as an HTML button, the default.
14931 * var button = new OO.ui.ButtonInputWidget( {
14932 * label: 'Input button',
14936 * $( 'body' ).append( button.$element );
14938 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
14941 * @extends OO.ui.InputWidget
14942 * @mixins OO.ui.mixin.ButtonElement
14943 * @mixins OO.ui.mixin.IconElement
14944 * @mixins OO.ui.mixin.IndicatorElement
14945 * @mixins OO.ui.mixin.LabelElement
14946 * @mixins OO.ui.mixin.TitledElement
14949 * @param {Object} [config] Configuration options
14950 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
14951 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
14952 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
14953 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
14954 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
14956 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
14957 // Configuration initialization
14958 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
14960 // Properties (must be set before parent constructor, which calls #setValue)
14961 this.useInputTag
= config
.useInputTag
;
14963 // Parent constructor
14964 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
14966 // Mixin constructors
14967 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
14968 OO
.ui
.mixin
.IconElement
.call( this, config
);
14969 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
14970 OO
.ui
.mixin
.LabelElement
.call( this, config
);
14971 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
14974 if ( !config
.useInputTag
) {
14975 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
14977 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
14982 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
14983 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
14984 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
14985 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
14986 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
14987 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
14989 /* Static Properties */
14992 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
14993 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
14995 OO
.ui
.ButtonInputWidget
.static.supportsSimpleLabel
= false;
15003 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
15005 // See InputWidget#reusePreInfuseDOM about config.$input
15006 if ( config
.$input
) {
15007 return config
.$input
.empty();
15009 type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ? config
.type
: 'button';
15010 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
15016 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
15018 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
15019 * text, or `null` for no label
15022 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
15023 OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
15025 if ( this.useInputTag
) {
15026 if ( typeof label
=== 'function' ) {
15027 label
= OO
.ui
.resolveMsg( label
);
15029 if ( label
instanceof jQuery
) {
15030 label
= label
.text();
15035 this.$input
.val( label
);
15042 * Set the value of the input.
15044 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
15045 * they do not support {@link #value values}.
15047 * @param {string} value New value
15050 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
15051 if ( !this.useInputTag
) {
15052 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
15058 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
15059 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
15060 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
15061 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
15063 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15066 * // An example of selected, unselected, and disabled checkbox inputs
15067 * var checkbox1=new OO.ui.CheckboxInputWidget( {
15071 * var checkbox2=new OO.ui.CheckboxInputWidget( {
15074 * var checkbox3=new OO.ui.CheckboxInputWidget( {
15078 * // Create a fieldset layout with fields for each checkbox.
15079 * var fieldset = new OO.ui.FieldsetLayout( {
15080 * label: 'Checkboxes'
15082 * fieldset.addItems( [
15083 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
15084 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
15085 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
15087 * $( 'body' ).append( fieldset.$element );
15089 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15092 * @extends OO.ui.InputWidget
15095 * @param {Object} [config] Configuration options
15096 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
15098 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
15099 // Configuration initialization
15100 config
= config
|| {};
15102 // Parent constructor
15103 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
15107 .addClass( 'oo-ui-checkboxInputWidget' )
15108 // Required for pretty styling in MediaWiki theme
15109 .append( $( '<span>' ) );
15110 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
15115 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
15117 /* Static Methods */
15122 OO
.ui
.CheckboxInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
15123 var state
= OO
.ui
.CheckboxInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
15124 state
.checked
= config
.$input
.prop( 'checked' );
15134 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
15135 return $( '<input type="checkbox" />' );
15141 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
15143 if ( !this.isDisabled() ) {
15144 // Allow the stack to clear so the value will be updated
15145 setTimeout( function () {
15146 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
15152 * Set selection state of this checkbox.
15154 * @param {boolean} state `true` for selected
15157 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
15159 if ( this.selected
!== state
) {
15160 this.selected
= state
;
15161 this.$input
.prop( 'checked', this.selected
);
15162 this.emit( 'change', this.selected
);
15168 * Check if this checkbox is selected.
15170 * @return {boolean} Checkbox is selected
15172 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
15173 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
15174 // it, and we won't know unless they're kind enough to trigger a 'change' event.
15175 var selected
= this.$input
.prop( 'checked' );
15176 if ( this.selected
!== selected
) {
15177 this.setSelected( selected
);
15179 return this.selected
;
15185 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
15186 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
15187 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
15188 this.setSelected( state
.checked
);
15193 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
15194 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15195 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15196 * more information about input widgets.
15198 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
15199 * are no options. If no `value` configuration option is provided, the first option is selected.
15200 * If you need a state representing no value (no option being selected), use a DropdownWidget.
15202 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
15205 * // Example: A DropdownInputWidget with three options
15206 * var dropdownInput = new OO.ui.DropdownInputWidget( {
15208 * { data: 'a', label: 'First' },
15209 * { data: 'b', label: 'Second'},
15210 * { data: 'c', label: 'Third' }
15213 * $( 'body' ).append( dropdownInput.$element );
15215 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15218 * @extends OO.ui.InputWidget
15219 * @mixins OO.ui.mixin.TitledElement
15222 * @param {Object} [config] Configuration options
15223 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15224 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
15226 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
15227 // Configuration initialization
15228 config
= config
|| {};
15230 // Properties (must be done before parent constructor which calls #setDisabled)
15231 this.dropdownWidget
= new OO
.ui
.DropdownWidget( config
.dropdown
);
15233 // Parent constructor
15234 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
15236 // Mixin constructors
15237 OO
.ui
.mixin
.TitledElement
.call( this, config
);
15240 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
15243 this.setOptions( config
.options
|| [] );
15245 .addClass( 'oo-ui-dropdownInputWidget' )
15246 .append( this.dropdownWidget
.$element
);
15251 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
15252 OO
.mixinClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.mixin
.TitledElement
);
15260 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function ( config
) {
15261 // See InputWidget#reusePreInfuseDOM about config.$input
15262 if ( config
.$input
) {
15263 return config
.$input
.addClass( 'oo-ui-element-hidden' );
15265 return $( '<input type="hidden">' );
15269 * Handles menu select events.
15272 * @param {OO.ui.MenuOptionWidget} item Selected menu item
15274 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
15275 this.setValue( item
.getData() );
15281 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
15282 value
= this.cleanUpValue( value
);
15283 this.dropdownWidget
.getMenu().selectItemByData( value
);
15284 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
15291 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
15292 this.dropdownWidget
.setDisabled( state
);
15293 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
15298 * Set the options available for this input.
15300 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15303 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
15305 value
= this.getValue(),
15308 // Rebuild the dropdown menu
15309 this.dropdownWidget
.getMenu()
15311 .addItems( options
.map( function ( opt
) {
15312 var optValue
= widget
.cleanUpValue( opt
.data
);
15313 return new OO
.ui
.MenuOptionWidget( {
15315 label
: opt
.label
!== undefined ? opt
.label
: optValue
15319 // Restore the previous value, or reset to something sensible
15320 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
15321 // Previous value is still available, ensure consistency with the dropdown
15322 this.setValue( value
);
15324 // No longer valid, reset
15325 if ( options
.length
) {
15326 this.setValue( options
[ 0 ].data
);
15336 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
15337 this.dropdownWidget
.getMenu().toggle( true );
15344 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
15345 this.dropdownWidget
.getMenu().toggle( false );
15350 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
15351 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
15352 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
15353 * please see the [OOjs UI documentation on MediaWiki][1].
15355 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15358 * // An example of selected, unselected, and disabled radio inputs
15359 * var radio1 = new OO.ui.RadioInputWidget( {
15363 * var radio2 = new OO.ui.RadioInputWidget( {
15366 * var radio3 = new OO.ui.RadioInputWidget( {
15370 * // Create a fieldset layout with fields for each radio button.
15371 * var fieldset = new OO.ui.FieldsetLayout( {
15372 * label: 'Radio inputs'
15374 * fieldset.addItems( [
15375 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
15376 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
15377 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
15379 * $( 'body' ).append( fieldset.$element );
15381 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15384 * @extends OO.ui.InputWidget
15387 * @param {Object} [config] Configuration options
15388 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
15390 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
15391 // Configuration initialization
15392 config
= config
|| {};
15394 // Parent constructor
15395 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
15399 .addClass( 'oo-ui-radioInputWidget' )
15400 // Required for pretty styling in MediaWiki theme
15401 .append( $( '<span>' ) );
15402 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
15407 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
15409 /* Static Methods */
15414 OO
.ui
.RadioInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
15415 var state
= OO
.ui
.RadioInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
15416 state
.checked
= config
.$input
.prop( 'checked' );
15426 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
15427 return $( '<input type="radio" />' );
15433 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
15434 // RadioInputWidget doesn't track its state.
15438 * Set selection state of this radio button.
15440 * @param {boolean} state `true` for selected
15443 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
15444 // RadioInputWidget doesn't track its state.
15445 this.$input
.prop( 'checked', state
);
15450 * Check if this radio button is selected.
15452 * @return {boolean} Radio is selected
15454 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
15455 return this.$input
.prop( 'checked' );
15461 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
15462 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
15463 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
15464 this.setSelected( state
.checked
);
15469 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
15470 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15471 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15472 * more information about input widgets.
15474 * This and OO.ui.DropdownInputWidget support the same configuration options.
15477 * // Example: A RadioSelectInputWidget with three options
15478 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
15480 * { data: 'a', label: 'First' },
15481 * { data: 'b', label: 'Second'},
15482 * { data: 'c', label: 'Third' }
15485 * $( 'body' ).append( radioSelectInput.$element );
15487 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15490 * @extends OO.ui.InputWidget
15493 * @param {Object} [config] Configuration options
15494 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15496 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
15497 // Configuration initialization
15498 config
= config
|| {};
15500 // Properties (must be done before parent constructor which calls #setDisabled)
15501 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
15503 // Parent constructor
15504 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
15507 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
15510 this.setOptions( config
.options
|| [] );
15512 .addClass( 'oo-ui-radioSelectInputWidget' )
15513 .append( this.radioSelectWidget
.$element
);
15518 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
15520 /* Static Properties */
15522 OO
.ui
.RadioSelectInputWidget
.static.supportsSimpleLabel
= false;
15524 /* Static Methods */
15529 OO
.ui
.RadioSelectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
15530 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
15531 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
15541 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
15542 return $( '<input type="hidden">' );
15546 * Handles menu select events.
15549 * @param {OO.ui.RadioOptionWidget} item Selected menu item
15551 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
15552 this.setValue( item
.getData() );
15558 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
15559 value
= this.cleanUpValue( value
);
15560 this.radioSelectWidget
.selectItemByData( value
);
15561 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
15568 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
15569 this.radioSelectWidget
.setDisabled( state
);
15570 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
15575 * Set the options available for this input.
15577 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15580 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
15582 value
= this.getValue(),
15585 // Rebuild the radioSelect menu
15586 this.radioSelectWidget
15588 .addItems( options
.map( function ( opt
) {
15589 var optValue
= widget
.cleanUpValue( opt
.data
);
15590 return new OO
.ui
.RadioOptionWidget( {
15592 label
: opt
.label
!== undefined ? opt
.label
: optValue
15596 // Restore the previous value, or reset to something sensible
15597 if ( this.radioSelectWidget
.getItemFromData( value
) ) {
15598 // Previous value is still available, ensure consistency with the radioSelect
15599 this.setValue( value
);
15601 // No longer valid, reset
15602 if ( options
.length
) {
15603 this.setValue( options
[ 0 ].data
);
15611 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
15612 * size of the field as well as its presentation. In addition, these widgets can be configured
15613 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
15614 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
15615 * which modifies incoming values rather than validating them.
15616 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
15618 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15621 * // Example of a text input widget
15622 * var textInput = new OO.ui.TextInputWidget( {
15623 * value: 'Text input'
15625 * $( 'body' ).append( textInput.$element );
15627 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15630 * @extends OO.ui.InputWidget
15631 * @mixins OO.ui.mixin.IconElement
15632 * @mixins OO.ui.mixin.IndicatorElement
15633 * @mixins OO.ui.mixin.PendingElement
15634 * @mixins OO.ui.mixin.LabelElement
15637 * @param {Object} [config] Configuration options
15638 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
15639 * 'email' or 'url'. Ignored if `multiline` is true.
15641 * Some values of `type` result in additional behaviors:
15643 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
15644 * empties the text field
15645 * @cfg {string} [placeholder] Placeholder text
15646 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
15647 * instruct the browser to focus this widget.
15648 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
15649 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
15650 * @cfg {boolean} [multiline=false] Allow multiple lines of text
15651 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
15652 * specifies minimum number of rows to display.
15653 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
15654 * Use the #maxRows config to specify a maximum number of displayed rows.
15655 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
15656 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
15657 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
15658 * the value or placeholder text: `'before'` or `'after'`
15659 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
15660 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
15661 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
15662 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
15663 * (the value must contain only numbers); when RegExp, a regular expression that must match the
15664 * value for it to be considered valid; when Function, a function receiving the value as parameter
15665 * that must return true, or promise resolving to true, for it to be considered valid.
15667 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
15668 // Configuration initialization
15669 config
= $.extend( {
15671 labelPosition
: 'after'
15673 if ( config
.type
=== 'search' ) {
15674 if ( config
.icon
=== undefined ) {
15675 config
.icon
= 'search';
15677 // indicator: 'clear' is set dynamically later, depending on value
15679 if ( config
.required
) {
15680 if ( config
.indicator
=== undefined ) {
15681 config
.indicator
= 'required';
15685 // Parent constructor
15686 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
15688 // Mixin constructors
15689 OO
.ui
.mixin
.IconElement
.call( this, config
);
15690 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
15691 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
15692 OO
.ui
.mixin
.LabelElement
.call( this, config
);
15695 this.type
= this.getSaneType( config
);
15696 this.readOnly
= false;
15697 this.multiline
= !!config
.multiline
;
15698 this.autosize
= !!config
.autosize
;
15699 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
15700 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
15701 this.validate
= null;
15702 this.styleHeight
= null;
15703 this.scrollWidth
= null;
15705 // Clone for resizing
15706 if ( this.autosize
) {
15707 this.$clone
= this.$input
15709 .insertAfter( this.$input
)
15710 .attr( 'aria-hidden', 'true' )
15711 .addClass( 'oo-ui-element-hidden' );
15714 this.setValidation( config
.validate
);
15715 this.setLabelPosition( config
.labelPosition
);
15719 keypress
: this.onKeyPress
.bind( this ),
15720 blur
: this.onBlur
.bind( this )
15723 focus
: this.onElementAttach
.bind( this )
15725 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
15726 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
15727 this.on( 'labelChange', this.updatePosition
.bind( this ) );
15728 this.connect( this, {
15729 change
: 'onChange',
15730 disable
: 'onDisable'
15735 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
15736 .append( this.$icon
, this.$indicator
);
15737 this.setReadOnly( !!config
.readOnly
);
15738 this.updateSearchIndicator();
15739 if ( config
.placeholder
) {
15740 this.$input
.attr( 'placeholder', config
.placeholder
);
15742 if ( config
.maxLength
!== undefined ) {
15743 this.$input
.attr( 'maxlength', config
.maxLength
);
15745 if ( config
.autofocus
) {
15746 this.$input
.attr( 'autofocus', 'autofocus' );
15748 if ( config
.required
) {
15749 this.$input
.attr( 'required', 'required' );
15750 this.$input
.attr( 'aria-required', 'true' );
15752 if ( config
.autocomplete
=== false ) {
15753 this.$input
.attr( 'autocomplete', 'off' );
15754 // Turning off autocompletion also disables "form caching" when the user navigates to a
15755 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
15757 beforeunload: function () {
15758 this.$input
.removeAttr( 'autocomplete' );
15760 pageshow: function () {
15761 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
15762 // whole page... it shouldn't hurt, though.
15763 this.$input
.attr( 'autocomplete', 'off' );
15767 if ( this.multiline
&& config
.rows
) {
15768 this.$input
.attr( 'rows', config
.rows
);
15770 if ( this.label
|| config
.autosize
) {
15771 this.installParentChangeDetector();
15777 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
15778 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
15779 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
15780 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
15781 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
15783 /* Static Properties */
15785 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
15790 /* Static Methods */
15795 OO
.ui
.TextInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
15796 var state
= OO
.ui
.TextInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
15797 if ( config
.multiline
) {
15798 state
.scrollTop
= config
.$input
.scrollTop();
15806 * An `enter` event is emitted when the user presses 'enter' inside the text box.
15808 * Not emitted if the input is multiline.
15814 * A `resize` event is emitted when autosize is set and the widget resizes
15822 * Handle icon mouse down events.
15825 * @param {jQuery.Event} e Mouse down event
15828 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
15829 if ( e
.which
=== 1 ) {
15830 this.$input
[ 0 ].focus();
15836 * Handle indicator mouse down events.
15839 * @param {jQuery.Event} e Mouse down event
15842 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
15843 if ( e
.which
=== 1 ) {
15844 if ( this.type
=== 'search' ) {
15845 // Clear the text field
15846 this.setValue( '' );
15848 this.$input
[ 0 ].focus();
15854 * Handle key press events.
15857 * @param {jQuery.Event} e Key press event
15858 * @fires enter If enter key is pressed and input is not multiline
15860 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
15861 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
15862 this.emit( 'enter', e
);
15867 * Handle blur events.
15870 * @param {jQuery.Event} e Blur event
15872 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
15873 this.setValidityFlag();
15877 * Handle element attach events.
15880 * @param {jQuery.Event} e Element attach event
15882 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
15883 // Any previously calculated size is now probably invalid if we reattached elsewhere
15884 this.valCache
= null;
15886 this.positionLabel();
15890 * Handle change events.
15892 * @param {string} value
15895 OO
.ui
.TextInputWidget
.prototype.onChange = function () {
15896 this.updateSearchIndicator();
15897 this.setValidityFlag();
15902 * Handle disable events.
15904 * @param {boolean} disabled Element is disabled
15907 OO
.ui
.TextInputWidget
.prototype.onDisable = function () {
15908 this.updateSearchIndicator();
15912 * Check if the input is {@link #readOnly read-only}.
15914 * @return {boolean}
15916 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
15917 return this.readOnly
;
15921 * Set the {@link #readOnly read-only} state of the input.
15923 * @param {boolean} state Make input read-only
15926 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
15927 this.readOnly
= !!state
;
15928 this.$input
.prop( 'readOnly', this.readOnly
);
15929 this.updateSearchIndicator();
15934 * Support function for making #onElementAttach work across browsers.
15936 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
15937 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
15939 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
15940 * first time that the element gets attached to the documented.
15942 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
15943 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
15944 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
15947 if ( MutationObserver
) {
15948 // The new way. If only it wasn't so ugly.
15950 if ( this.$element
.closest( 'html' ).length
) {
15951 // Widget is attached already, do nothing. This breaks the functionality of this function when
15952 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
15953 // would require observation of the whole document, which would hurt performance of other,
15954 // more important code.
15958 // Find topmost node in the tree
15959 topmostNode
= this.$element
[ 0 ];
15960 while ( topmostNode
.parentNode
) {
15961 topmostNode
= topmostNode
.parentNode
;
15964 // We have no way to detect the $element being attached somewhere without observing the entire
15965 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
15966 // parent node of $element, and instead detect when $element is removed from it (and thus
15967 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
15968 // doesn't get attached, we end up back here and create the parent.
15970 mutationObserver
= new MutationObserver( function ( mutations
) {
15971 var i
, j
, removedNodes
;
15972 for ( i
= 0; i
< mutations
.length
; i
++ ) {
15973 removedNodes
= mutations
[ i
].removedNodes
;
15974 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
15975 if ( removedNodes
[ j
] === topmostNode
) {
15976 setTimeout( onRemove
, 0 );
15983 onRemove = function () {
15984 // If the node was attached somewhere else, report it
15985 if ( widget
.$element
.closest( 'html' ).length
) {
15986 widget
.onElementAttach();
15988 mutationObserver
.disconnect();
15989 widget
.installParentChangeDetector();
15992 // Create a fake parent and observe it
15993 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
15994 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
15996 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
15997 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
15998 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
16003 * Automatically adjust the size of the text input.
16005 * This only affects #multiline inputs that are {@link #autosize autosized}.
16010 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
16011 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
,
16012 idealHeight
, newHeight
, scrollWidth
, property
;
16014 if ( this.multiline
&& this.$input
.val() !== this.valCache
) {
16015 if ( this.autosize
) {
16017 .val( this.$input
.val() )
16018 .attr( 'rows', this.minRows
)
16019 // Set inline height property to 0 to measure scroll height
16020 .css( 'height', 0 );
16022 this.$clone
.removeClass( 'oo-ui-element-hidden' );
16024 this.valCache
= this.$input
.val();
16026 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
16028 // Remove inline height property to measure natural heights
16029 this.$clone
.css( 'height', '' );
16030 innerHeight
= this.$clone
.innerHeight();
16031 outerHeight
= this.$clone
.outerHeight();
16033 // Measure max rows height
16035 .attr( 'rows', this.maxRows
)
16036 .css( 'height', 'auto' )
16038 maxInnerHeight
= this.$clone
.innerHeight();
16040 // Difference between reported innerHeight and scrollHeight with no scrollbars present
16041 // Equals 1 on Blink-based browsers and 0 everywhere else
16042 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
16043 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
16045 this.$clone
.addClass( 'oo-ui-element-hidden' );
16047 // Only apply inline height when expansion beyond natural height is needed
16048 // Use the difference between the inner and outer height as a buffer
16049 newHeight
= idealHeight
> innerHeight
? idealHeight
+ ( outerHeight
- innerHeight
) : '';
16050 if ( newHeight
!== this.styleHeight
) {
16051 this.$input
.css( 'height', newHeight
);
16052 this.styleHeight
= newHeight
;
16053 this.emit( 'resize' );
16056 scrollWidth
= this.$input
[ 0 ].offsetWidth
- this.$input
[ 0 ].clientWidth
;
16057 if ( scrollWidth
!== this.scrollWidth
) {
16058 property
= this.$element
.css( 'direction' ) === 'rtl' ? 'left' : 'right';
16060 this.$label
.css( { right
: '', left
: '' } );
16061 this.$indicator
.css( { right
: '', left
: '' } );
16063 if ( scrollWidth
) {
16064 this.$indicator
.css( property
, scrollWidth
);
16065 if ( this.labelPosition
=== 'after' ) {
16066 this.$label
.css( property
, scrollWidth
);
16070 this.scrollWidth
= scrollWidth
;
16071 this.positionLabel();
16081 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
16082 return config
.multiline
?
16083 $( '<textarea>' ) :
16084 $( '<input type="' + this.getSaneType( config
) + '" />' );
16088 * Get sanitized value for 'type' for given config.
16090 * @param {Object} config Configuration options
16091 * @return {string|null}
16094 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
16095 var type
= [ 'text', 'password', 'search', 'email', 'url' ].indexOf( config
.type
) !== -1 ?
16098 return config
.multiline
? 'multiline' : type
;
16102 * Check if the input supports multiple lines.
16104 * @return {boolean}
16106 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
16107 return !!this.multiline
;
16111 * Check if the input automatically adjusts its size.
16113 * @return {boolean}
16115 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
16116 return !!this.autosize
;
16120 * Focus the input and select a specified range within the text.
16122 * @param {number} from Select from offset
16123 * @param {number} [to] Select to offset, defaults to from
16126 OO
.ui
.TextInputWidget
.prototype.selectRange = function ( from, to
) {
16127 var textRange
, isBackwards
, start
, end
,
16128 element
= this.$input
[ 0 ];
16132 isBackwards
= to
< from;
16133 start
= isBackwards
? to
: from;
16134 end
= isBackwards
? from : to
;
16138 if ( element
.setSelectionRange
) {
16139 element
.setSelectionRange( start
, end
, isBackwards
? 'backward' : 'forward' );
16140 } else if ( element
.createTextRange
) {
16142 textRange
= element
.createTextRange();
16143 textRange
.collapse( true );
16144 textRange
.moveStart( 'character', start
);
16145 textRange
.moveEnd( 'character', end
- start
);
16146 textRange
.select();
16152 * Get the length of the text input value.
16154 * This could differ from the length of #getValue if the
16155 * value gets filtered
16157 * @return {number} Input length
16159 OO
.ui
.TextInputWidget
.prototype.getInputLength = function () {
16160 return this.$input
[ 0 ].value
.length
;
16164 * Focus the input and select the entire text.
16168 OO
.ui
.TextInputWidget
.prototype.select = function () {
16169 return this.selectRange( 0, this.getInputLength() );
16173 * Focus the input and move the cursor to the start.
16177 OO
.ui
.TextInputWidget
.prototype.moveCursorToStart = function () {
16178 return this.selectRange( 0 );
16182 * Focus the input and move the cursor to the end.
16186 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
16187 return this.selectRange( this.getInputLength() );
16191 * Set the validation pattern.
16193 * The validation pattern is either a regular expression, a function, or the symbolic name of a
16194 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
16195 * value must contain only numbers).
16197 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
16198 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
16200 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
16201 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
16202 this.validate
= validate
;
16204 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
16209 * Sets the 'invalid' flag appropriately.
16211 * @param {boolean} [isValid] Optionally override validation result
16213 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
16215 setFlag = function ( valid
) {
16217 widget
.$input
.attr( 'aria-invalid', 'true' );
16219 widget
.$input
.removeAttr( 'aria-invalid' );
16221 widget
.setFlags( { invalid
: !valid
} );
16224 if ( isValid
!== undefined ) {
16225 setFlag( isValid
);
16227 this.getValidity().then( function () {
16236 * Check if a value is valid.
16238 * This method returns a promise that resolves with a boolean `true` if the current value is
16239 * considered valid according to the supplied {@link #validate validation pattern}.
16242 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
16244 OO
.ui
.TextInputWidget
.prototype.isValid = function () {
16247 if ( this.validate
instanceof Function
) {
16248 result
= this.validate( this.getValue() );
16249 if ( $.isFunction( result
.promise
) ) {
16250 return result
.promise();
16252 return $.Deferred().resolve( !!result
).promise();
16255 return $.Deferred().resolve( !!this.getValue().match( this.validate
) ).promise();
16260 * Get the validity of current value.
16262 * This method returns a promise that resolves if the value is valid and rejects if
16263 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
16265 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
16267 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
16268 var result
, promise
;
16270 function rejectOrResolve( valid
) {
16272 return $.Deferred().resolve().promise();
16274 return $.Deferred().reject().promise();
16278 if ( this.validate
instanceof Function
) {
16279 result
= this.validate( this.getValue() );
16281 if ( $.isFunction( result
.promise
) ) {
16282 promise
= $.Deferred();
16284 result
.then( function ( valid
) {
16294 return promise
.promise();
16296 return rejectOrResolve( result
);
16299 return rejectOrResolve( this.getValue().match( this.validate
) );
16304 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
16306 * @param {string} labelPosition Label position, 'before' or 'after'
16309 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
16310 this.labelPosition
= labelPosition
;
16311 this.updatePosition();
16316 * Deprecated alias of #setLabelPosition
16318 * @deprecated Use setLabelPosition instead.
16320 OO
.ui
.TextInputWidget
.prototype.setPosition
=
16321 OO
.ui
.TextInputWidget
.prototype.setLabelPosition
;
16324 * Update the position of the inline label.
16326 * This method is called by #setLabelPosition, and can also be called on its own if
16327 * something causes the label to be mispositioned.
16331 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
16332 var after
= this.labelPosition
=== 'after';
16335 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
16336 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
16338 this.valCache
= null;
16339 this.scrollWidth
= null;
16341 this.positionLabel();
16347 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
16348 * already empty or when it's not editable.
16350 OO
.ui
.TextInputWidget
.prototype.updateSearchIndicator = function () {
16351 if ( this.type
=== 'search' ) {
16352 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
16353 this.setIndicator( null );
16355 this.setIndicator( 'clear' );
16361 * Position the label by setting the correct padding on the input.
16366 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
16367 var after
, rtl
, property
;
16368 // Clear old values
16370 // Clear old values if present
16372 'padding-right': '',
16376 if ( this.label
) {
16377 this.$element
.append( this.$label
);
16379 this.$label
.detach();
16383 after
= this.labelPosition
=== 'after';
16384 rtl
= this.$element
.css( 'direction' ) === 'rtl';
16385 property
= after
=== rtl
? 'padding-left' : 'padding-right';
16387 this.$input
.css( property
, this.$label
.outerWidth( true ) + ( after
? this.scrollWidth
: 0 ) );
16395 OO
.ui
.TextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
16396 OO
.ui
.TextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
16397 if ( state
.scrollTop
!== undefined ) {
16398 this.$input
.scrollTop( state
.scrollTop
);
16403 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
16404 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
16405 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
16407 * - by typing a value in the text input field. If the value exactly matches the value of a menu
16408 * option, that option will appear to be selected.
16409 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
16412 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
16414 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
16417 * // Example: A ComboBoxInputWidget.
16418 * var comboBox = new OO.ui.ComboBoxInputWidget( {
16419 * label: 'ComboBoxInputWidget',
16420 * value: 'Option 1',
16423 * new OO.ui.MenuOptionWidget( {
16424 * data: 'Option 1',
16425 * label: 'Option One'
16427 * new OO.ui.MenuOptionWidget( {
16428 * data: 'Option 2',
16429 * label: 'Option Two'
16431 * new OO.ui.MenuOptionWidget( {
16432 * data: 'Option 3',
16433 * label: 'Option Three'
16435 * new OO.ui.MenuOptionWidget( {
16436 * data: 'Option 4',
16437 * label: 'Option Four'
16439 * new OO.ui.MenuOptionWidget( {
16440 * data: 'Option 5',
16441 * label: 'Option Five'
16446 * $( 'body' ).append( comboBox.$element );
16448 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16451 * @extends OO.ui.TextInputWidget
16454 * @param {Object} [config] Configuration options
16455 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
16456 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
16457 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
16458 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
16459 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
16461 OO
.ui
.ComboBoxInputWidget
= function OoUiComboBoxInputWidget( config
) {
16462 // Configuration initialization
16463 config
= $.extend( {
16466 // For backwards-compatibility with ComboBoxWidget config
16467 $.extend( config
, config
.input
);
16469 // Parent constructor
16470 OO
.ui
.ComboBoxInputWidget
.parent
.call( this, config
);
16473 this.$overlay
= config
.$overlay
|| this.$element
;
16474 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
16478 $container
: this.$element
,
16479 disabled
: this.isDisabled()
16483 // For backwards-compatibility with ComboBoxWidget
16487 this.$indicator
.on( {
16488 click
: this.onIndicatorClick
.bind( this ),
16489 keypress
: this.onIndicatorKeyPress
.bind( this )
16491 this.connect( this, {
16492 change
: 'onInputChange',
16493 enter
: 'onInputEnter'
16495 this.menu
.connect( this, {
16496 choose
: 'onMenuChoose',
16497 add
: 'onMenuItemsChange',
16498 remove
: 'onMenuItemsChange'
16502 this.$input
.attr( {
16504 'aria-autocomplete': 'list'
16506 // Do not override options set via config.menu.items
16507 if ( config
.options
!== undefined ) {
16508 this.setOptions( config
.options
);
16510 // Extra class for backwards-compatibility with ComboBoxWidget
16511 this.$element
.addClass( 'oo-ui-comboBoxInputWidget oo-ui-comboBoxWidget' );
16512 this.$overlay
.append( this.menu
.$element
);
16513 this.onMenuItemsChange();
16518 OO
.inheritClass( OO
.ui
.ComboBoxInputWidget
, OO
.ui
.TextInputWidget
);
16523 * Get the combobox's menu.
16524 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
16526 OO
.ui
.ComboBoxInputWidget
.prototype.getMenu = function () {
16531 * Get the combobox's text input widget.
16532 * @return {OO.ui.TextInputWidget} Text input widget
16534 OO
.ui
.ComboBoxInputWidget
.prototype.getInput = function () {
16539 * Handle input change events.
16542 * @param {string} value New value
16544 OO
.ui
.ComboBoxInputWidget
.prototype.onInputChange = function ( value
) {
16545 var match
= this.menu
.getItemFromData( value
);
16547 this.menu
.selectItem( match
);
16548 if ( this.menu
.getHighlightedItem() ) {
16549 this.menu
.highlightItem( match
);
16552 if ( !this.isDisabled() ) {
16553 this.menu
.toggle( true );
16558 * Handle mouse click events.
16561 * @param {jQuery.Event} e Mouse click event
16563 OO
.ui
.ComboBoxInputWidget
.prototype.onIndicatorClick = function ( e
) {
16564 if ( !this.isDisabled() && e
.which
=== 1 ) {
16565 this.menu
.toggle();
16566 this.$input
[ 0 ].focus();
16572 * Handle key press events.
16575 * @param {jQuery.Event} e Key press event
16577 OO
.ui
.ComboBoxInputWidget
.prototype.onIndicatorKeyPress = function ( e
) {
16578 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
16579 this.menu
.toggle();
16580 this.$input
[ 0 ].focus();
16586 * Handle input enter events.
16590 OO
.ui
.ComboBoxInputWidget
.prototype.onInputEnter = function () {
16591 if ( !this.isDisabled() ) {
16592 this.menu
.toggle( false );
16597 * Handle menu choose events.
16600 * @param {OO.ui.OptionWidget} item Chosen item
16602 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuChoose = function ( item
) {
16603 this.setValue( item
.getData() );
16607 * Handle menu item change events.
16611 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuItemsChange = function () {
16612 var match
= this.menu
.getItemFromData( this.getValue() );
16613 this.menu
.selectItem( match
);
16614 if ( this.menu
.getHighlightedItem() ) {
16615 this.menu
.highlightItem( match
);
16617 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu
.isEmpty() );
16623 OO
.ui
.ComboBoxInputWidget
.prototype.setDisabled = function ( disabled
) {
16625 OO
.ui
.ComboBoxInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
16628 this.menu
.setDisabled( this.isDisabled() );
16635 * Set the options available for this input.
16637 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
16640 OO
.ui
.ComboBoxInputWidget
.prototype.setOptions = function ( options
) {
16643 .addItems( options
.map( function ( opt
) {
16644 return new OO
.ui
.MenuOptionWidget( {
16646 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
16655 * @deprecated Use OO.ui.ComboBoxInputWidget instead.
16657 OO
.ui
.ComboBoxWidget
= OO
.ui
.ComboBoxInputWidget
;
16660 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
16661 * be configured with a `label` option that is set to a string, a label node, or a function:
16663 * - String: a plaintext string
16664 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
16665 * label that includes a link or special styling, such as a gray color or additional graphical elements.
16666 * - Function: a function that will produce a string in the future. Functions are used
16667 * in cases where the value of the label is not currently defined.
16669 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
16670 * will come into focus when the label is clicked.
16673 * // Examples of LabelWidgets
16674 * var label1 = new OO.ui.LabelWidget( {
16675 * label: 'plaintext label'
16677 * var label2 = new OO.ui.LabelWidget( {
16678 * label: $( '<a href="default.html">jQuery label</a>' )
16680 * // Create a fieldset layout with fields for each example
16681 * var fieldset = new OO.ui.FieldsetLayout();
16682 * fieldset.addItems( [
16683 * new OO.ui.FieldLayout( label1 ),
16684 * new OO.ui.FieldLayout( label2 )
16686 * $( 'body' ).append( fieldset.$element );
16689 * @extends OO.ui.Widget
16690 * @mixins OO.ui.mixin.LabelElement
16693 * @param {Object} [config] Configuration options
16694 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
16695 * Clicking the label will focus the specified input field.
16697 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
16698 // Configuration initialization
16699 config
= config
|| {};
16701 // Parent constructor
16702 OO
.ui
.LabelWidget
.parent
.call( this, config
);
16704 // Mixin constructors
16705 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
16706 OO
.ui
.mixin
.TitledElement
.call( this, config
);
16709 this.input
= config
.input
;
16712 if ( this.input
instanceof OO
.ui
.InputWidget
) {
16713 this.$element
.on( 'click', this.onClick
.bind( this ) );
16717 this.$element
.addClass( 'oo-ui-labelWidget' );
16722 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
16723 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
16724 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
16726 /* Static Properties */
16728 OO
.ui
.LabelWidget
.static.tagName
= 'span';
16733 * Handles label mouse click events.
16736 * @param {jQuery.Event} e Mouse click event
16738 OO
.ui
.LabelWidget
.prototype.onClick = function () {
16739 this.input
.simulateLabelClick();
16744 * OptionWidgets are special elements that can be selected and configured with data. The
16745 * data is often unique for each option, but it does not have to be. OptionWidgets are used
16746 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
16747 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
16749 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16752 * @extends OO.ui.Widget
16753 * @mixins OO.ui.mixin.LabelElement
16754 * @mixins OO.ui.mixin.FlaggedElement
16757 * @param {Object} [config] Configuration options
16759 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
16760 // Configuration initialization
16761 config
= config
|| {};
16763 // Parent constructor
16764 OO
.ui
.OptionWidget
.parent
.call( this, config
);
16766 // Mixin constructors
16767 OO
.ui
.mixin
.ItemWidget
.call( this );
16768 OO
.ui
.mixin
.LabelElement
.call( this, config
);
16769 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
16772 this.selected
= false;
16773 this.highlighted
= false;
16774 this.pressed
= false;
16778 .data( 'oo-ui-optionWidget', this )
16779 .attr( 'role', 'option' )
16780 .attr( 'aria-selected', 'false' )
16781 .addClass( 'oo-ui-optionWidget' )
16782 .append( this.$label
);
16787 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
16788 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
16789 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
16790 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
16792 /* Static Properties */
16794 OO
.ui
.OptionWidget
.static.selectable
= true;
16796 OO
.ui
.OptionWidget
.static.highlightable
= true;
16798 OO
.ui
.OptionWidget
.static.pressable
= true;
16800 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
16805 * Check if the option can be selected.
16807 * @return {boolean} Item is selectable
16809 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
16810 return this.constructor.static.selectable
&& !this.isDisabled() && this.isVisible();
16814 * Check if the option can be highlighted. A highlight indicates that the option
16815 * may be selected when a user presses enter or clicks. Disabled items cannot
16818 * @return {boolean} Item is highlightable
16820 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
16821 return this.constructor.static.highlightable
&& !this.isDisabled() && this.isVisible();
16825 * Check if the option can be pressed. The pressed state occurs when a user mouses
16826 * down on an item, but has not yet let go of the mouse.
16828 * @return {boolean} Item is pressable
16830 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
16831 return this.constructor.static.pressable
&& !this.isDisabled() && this.isVisible();
16835 * Check if the option is selected.
16837 * @return {boolean} Item is selected
16839 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
16840 return this.selected
;
16844 * Check if the option is highlighted. A highlight indicates that the
16845 * item may be selected when a user presses enter or clicks.
16847 * @return {boolean} Item is highlighted
16849 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
16850 return this.highlighted
;
16854 * Check if the option is pressed. The pressed state occurs when a user mouses
16855 * down on an item, but has not yet let go of the mouse. The item may appear
16856 * selected, but it will not be selected until the user releases the mouse.
16858 * @return {boolean} Item is pressed
16860 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
16861 return this.pressed
;
16865 * Set the option’s selected state. In general, all modifications to the selection
16866 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
16867 * method instead of this method.
16869 * @param {boolean} [state=false] Select option
16872 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
16873 if ( this.constructor.static.selectable
) {
16874 this.selected
= !!state
;
16876 .toggleClass( 'oo-ui-optionWidget-selected', state
)
16877 .attr( 'aria-selected', state
.toString() );
16878 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
16879 this.scrollElementIntoView();
16881 this.updateThemeClasses();
16887 * Set the option’s highlighted state. In general, all programmatic
16888 * modifications to the highlight should be handled by the
16889 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
16890 * method instead of this method.
16892 * @param {boolean} [state=false] Highlight option
16895 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
16896 if ( this.constructor.static.highlightable
) {
16897 this.highlighted
= !!state
;
16898 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
16899 this.updateThemeClasses();
16905 * Set the option’s pressed state. In general, all
16906 * programmatic modifications to the pressed state should be handled by the
16907 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
16908 * method instead of this method.
16910 * @param {boolean} [state=false] Press option
16913 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
16914 if ( this.constructor.static.pressable
) {
16915 this.pressed
= !!state
;
16916 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
16917 this.updateThemeClasses();
16923 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
16924 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
16925 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
16926 * options. For more information about options and selects, please see the
16927 * [OOjs UI documentation on MediaWiki][1].
16930 * // Decorated options in a select widget
16931 * var select = new OO.ui.SelectWidget( {
16933 * new OO.ui.DecoratedOptionWidget( {
16935 * label: 'Option with icon',
16938 * new OO.ui.DecoratedOptionWidget( {
16940 * label: 'Option with indicator',
16941 * indicator: 'next'
16945 * $( 'body' ).append( select.$element );
16947 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16950 * @extends OO.ui.OptionWidget
16951 * @mixins OO.ui.mixin.IconElement
16952 * @mixins OO.ui.mixin.IndicatorElement
16955 * @param {Object} [config] Configuration options
16957 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
16958 // Parent constructor
16959 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
16961 // Mixin constructors
16962 OO
.ui
.mixin
.IconElement
.call( this, config
);
16963 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
16967 .addClass( 'oo-ui-decoratedOptionWidget' )
16968 .prepend( this.$icon
)
16969 .append( this.$indicator
);
16974 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
16975 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
16976 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
16979 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
16980 * can be selected and configured with data. The class is
16981 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
16982 * [OOjs UI documentation on MediaWiki] [1] for more information.
16984 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
16987 * @extends OO.ui.DecoratedOptionWidget
16988 * @mixins OO.ui.mixin.ButtonElement
16989 * @mixins OO.ui.mixin.TabIndexedElement
16990 * @mixins OO.ui.mixin.TitledElement
16993 * @param {Object} [config] Configuration options
16995 OO
.ui
.ButtonOptionWidget
= function OoUiButtonOptionWidget( config
) {
16996 // Configuration initialization
16997 config
= config
|| {};
16999 // Parent constructor
17000 OO
.ui
.ButtonOptionWidget
.parent
.call( this, config
);
17002 // Mixin constructors
17003 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
17004 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
17005 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, {
17006 $tabIndexed
: this.$button
,
17011 this.$element
.addClass( 'oo-ui-buttonOptionWidget' );
17012 this.$button
.append( this.$element
.contents() );
17013 this.$element
.append( this.$button
);
17018 OO
.inheritClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
17019 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.ButtonElement
);
17020 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.TitledElement
);
17021 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.TabIndexedElement
);
17023 /* Static Properties */
17025 // Allow button mouse down events to pass through so they can be handled by the parent select widget
17026 OO
.ui
.ButtonOptionWidget
.static.cancelButtonMouseDownEvents
= false;
17028 OO
.ui
.ButtonOptionWidget
.static.highlightable
= false;
17035 OO
.ui
.ButtonOptionWidget
.prototype.setSelected = function ( state
) {
17036 OO
.ui
.ButtonOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
17038 if ( this.constructor.static.selectable
) {
17039 this.setActive( state
);
17046 * RadioOptionWidget is an option widget that looks like a radio button.
17047 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
17048 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
17050 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
17053 * @extends OO.ui.OptionWidget
17056 * @param {Object} [config] Configuration options
17058 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
17059 // Configuration initialization
17060 config
= config
|| {};
17062 // Properties (must be done before parent constructor which calls #setDisabled)
17063 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
17065 // Parent constructor
17066 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
17069 this.radio
.$input
.on( 'focus', this.onInputFocus
.bind( this ) );
17072 // Remove implicit role, we're handling it ourselves
17073 this.radio
.$input
.attr( 'role', 'presentation' );
17075 .addClass( 'oo-ui-radioOptionWidget' )
17076 .attr( 'role', 'radio' )
17077 .attr( 'aria-checked', 'false' )
17078 .removeAttr( 'aria-selected' )
17079 .prepend( this.radio
.$element
);
17084 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
17086 /* Static Properties */
17088 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
17090 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
17092 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
17094 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
17099 * @param {jQuery.Event} e Focus event
17102 OO
.ui
.RadioOptionWidget
.prototype.onInputFocus = function () {
17103 this.radio
.$input
.blur();
17104 this.$element
.parent().focus();
17110 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
17111 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
17113 this.radio
.setSelected( state
);
17115 .attr( 'aria-checked', state
.toString() )
17116 .removeAttr( 'aria-selected' );
17124 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
17125 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
17127 this.radio
.setDisabled( this.isDisabled() );
17133 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
17134 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
17135 * the [OOjs UI documentation on MediaWiki] [1] for more information.
17137 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
17140 * @extends OO.ui.DecoratedOptionWidget
17143 * @param {Object} [config] Configuration options
17145 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
17146 // Configuration initialization
17147 config
= $.extend( { icon
: 'check' }, config
);
17149 // Parent constructor
17150 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
17154 .attr( 'role', 'menuitem' )
17155 .addClass( 'oo-ui-menuOptionWidget' );
17160 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
17162 /* Static Properties */
17164 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
17167 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
17168 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
17171 * var myDropdown = new OO.ui.DropdownWidget( {
17174 * new OO.ui.MenuSectionOptionWidget( {
17177 * new OO.ui.MenuOptionWidget( {
17179 * label: 'Welsh Corgi'
17181 * new OO.ui.MenuOptionWidget( {
17183 * label: 'Standard Poodle'
17185 * new OO.ui.MenuSectionOptionWidget( {
17188 * new OO.ui.MenuOptionWidget( {
17195 * $( 'body' ).append( myDropdown.$element );
17198 * @extends OO.ui.DecoratedOptionWidget
17201 * @param {Object} [config] Configuration options
17203 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
17204 // Parent constructor
17205 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
17208 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' );
17213 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
17215 /* Static Properties */
17217 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
17219 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
17222 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
17224 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
17225 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
17229 * @extends OO.ui.DecoratedOptionWidget
17232 * @param {Object} [config] Configuration options
17233 * @cfg {number} [level] Indentation level
17234 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
17236 OO
.ui
.OutlineOptionWidget
= function OoUiOutlineOptionWidget( config
) {
17237 // Configuration initialization
17238 config
= config
|| {};
17240 // Parent constructor
17241 OO
.ui
.OutlineOptionWidget
.parent
.call( this, config
);
17245 this.movable
= !!config
.movable
;
17246 this.removable
= !!config
.removable
;
17249 this.$element
.addClass( 'oo-ui-outlineOptionWidget' );
17250 this.setLevel( config
.level
);
17255 OO
.inheritClass( OO
.ui
.OutlineOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
17257 /* Static Properties */
17259 OO
.ui
.OutlineOptionWidget
.static.highlightable
= false;
17261 OO
.ui
.OutlineOptionWidget
.static.scrollIntoViewOnSelect
= true;
17263 OO
.ui
.OutlineOptionWidget
.static.levelClass
= 'oo-ui-outlineOptionWidget-level-';
17265 OO
.ui
.OutlineOptionWidget
.static.levels
= 3;
17270 * Check if item is movable.
17272 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17274 * @return {boolean} Item is movable
17276 OO
.ui
.OutlineOptionWidget
.prototype.isMovable = function () {
17277 return this.movable
;
17281 * Check if item is removable.
17283 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17285 * @return {boolean} Item is removable
17287 OO
.ui
.OutlineOptionWidget
.prototype.isRemovable = function () {
17288 return this.removable
;
17292 * Get indentation level.
17294 * @return {number} Indentation level
17296 OO
.ui
.OutlineOptionWidget
.prototype.getLevel = function () {
17303 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17305 * @param {boolean} movable Item is movable
17308 OO
.ui
.OutlineOptionWidget
.prototype.setMovable = function ( movable
) {
17309 this.movable
= !!movable
;
17310 this.updateThemeClasses();
17315 * Set removability.
17317 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17319 * @param {boolean} movable Item is removable
17322 OO
.ui
.OutlineOptionWidget
.prototype.setRemovable = function ( removable
) {
17323 this.removable
= !!removable
;
17324 this.updateThemeClasses();
17329 * Set indentation level.
17331 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
17334 OO
.ui
.OutlineOptionWidget
.prototype.setLevel = function ( level
) {
17335 var levels
= this.constructor.static.levels
,
17336 levelClass
= this.constructor.static.levelClass
,
17339 this.level
= level
? Math
.max( 0, Math
.min( levels
- 1, level
) ) : 0;
17341 if ( this.level
=== i
) {
17342 this.$element
.addClass( levelClass
+ i
);
17344 this.$element
.removeClass( levelClass
+ i
);
17347 this.updateThemeClasses();
17353 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
17355 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
17356 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
17360 * @extends OO.ui.OptionWidget
17363 * @param {Object} [config] Configuration options
17365 OO
.ui
.TabOptionWidget
= function OoUiTabOptionWidget( config
) {
17366 // Configuration initialization
17367 config
= config
|| {};
17369 // Parent constructor
17370 OO
.ui
.TabOptionWidget
.parent
.call( this, config
);
17373 this.$element
.addClass( 'oo-ui-tabOptionWidget' );
17378 OO
.inheritClass( OO
.ui
.TabOptionWidget
, OO
.ui
.OptionWidget
);
17380 /* Static Properties */
17382 OO
.ui
.TabOptionWidget
.static.highlightable
= false;
17385 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
17386 * By default, each popup has an anchor that points toward its origin.
17387 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
17390 * // A popup widget.
17391 * var popup = new OO.ui.PopupWidget( {
17392 * $content: $( '<p>Hi there!</p>' ),
17397 * $( 'body' ).append( popup.$element );
17398 * // To display the popup, toggle the visibility to 'true'.
17399 * popup.toggle( true );
17401 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
17404 * @extends OO.ui.Widget
17405 * @mixins OO.ui.mixin.LabelElement
17406 * @mixins OO.ui.mixin.ClippableElement
17409 * @param {Object} [config] Configuration options
17410 * @cfg {number} [width=320] Width of popup in pixels
17411 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
17412 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
17413 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
17414 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
17415 * popup is leaning towards the right of the screen.
17416 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
17417 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
17418 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
17419 * sentence in the given language.
17420 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
17421 * See the [OOjs UI docs on MediaWiki][3] for an example.
17422 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
17423 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
17424 * @cfg {jQuery} [$content] Content to append to the popup's body
17425 * @cfg {jQuery} [$footer] Content to append to the popup's footer
17426 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
17427 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
17428 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
17430 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
17431 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
17433 * @cfg {boolean} [padded] Add padding to the popup's body
17435 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
17436 // Configuration initialization
17437 config
= config
|| {};
17439 // Parent constructor
17440 OO
.ui
.PopupWidget
.parent
.call( this, config
);
17442 // Properties (must be set before ClippableElement constructor call)
17443 this.$body
= $( '<div>' );
17444 this.$popup
= $( '<div>' );
17446 // Mixin constructors
17447 OO
.ui
.mixin
.LabelElement
.call( this, config
);
17448 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, {
17449 $clippable
: this.$body
,
17450 $clippableContainer
: this.$popup
17454 this.$head
= $( '<div>' );
17455 this.$footer
= $( '<div>' );
17456 this.$anchor
= $( '<div>' );
17457 // If undefined, will be computed lazily in updateDimensions()
17458 this.$container
= config
.$container
;
17459 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
17460 this.autoClose
= !!config
.autoClose
;
17461 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
17462 this.transitionTimeout
= null;
17463 this.anchor
= null;
17464 this.width
= config
.width
!== undefined ? config
.width
: 320;
17465 this.height
= config
.height
!== undefined ? config
.height
: null;
17466 this.setAlignment( config
.align
);
17467 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
17468 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
17469 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
17472 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
17475 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
17476 this.$body
.addClass( 'oo-ui-popupWidget-body' );
17477 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
17479 .addClass( 'oo-ui-popupWidget-head' )
17480 .append( this.$label
, this.closeButton
.$element
);
17481 this.$footer
.addClass( 'oo-ui-popupWidget-footer' );
17482 if ( !config
.head
) {
17483 this.$head
.addClass( 'oo-ui-element-hidden' );
17485 if ( !config
.$footer
) {
17486 this.$footer
.addClass( 'oo-ui-element-hidden' );
17489 .addClass( 'oo-ui-popupWidget-popup' )
17490 .append( this.$head
, this.$body
, this.$footer
);
17492 .addClass( 'oo-ui-popupWidget' )
17493 .append( this.$popup
, this.$anchor
);
17494 // Move content, which was added to #$element by OO.ui.Widget, to the body
17495 if ( config
.$content
instanceof jQuery
) {
17496 this.$body
.append( config
.$content
);
17498 if ( config
.$footer
instanceof jQuery
) {
17499 this.$footer
.append( config
.$footer
);
17501 if ( config
.padded
) {
17502 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
17505 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
17506 // that reference properties not initialized at that time of parent class construction
17507 // TODO: Find a better way to handle post-constructor setup
17508 this.visible
= false;
17509 this.$element
.addClass( 'oo-ui-element-hidden' );
17514 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
17515 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
17516 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
17521 * Handles mouse down events.
17524 * @param {MouseEvent} e Mouse down event
17526 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
17528 this.isVisible() &&
17529 !$.contains( this.$element
[ 0 ], e
.target
) &&
17530 ( !this.$autoCloseIgnore
|| !this.$autoCloseIgnore
.has( e
.target
).length
)
17532 this.toggle( false );
17537 * Bind mouse down listener.
17541 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
17542 // Capture clicks outside popup
17543 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler
);
17547 * Handles close button click events.
17551 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
17552 if ( this.isVisible() ) {
17553 this.toggle( false );
17558 * Unbind mouse down listener.
17562 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
17563 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler
);
17567 * Handles key down events.
17570 * @param {KeyboardEvent} e Key down event
17572 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
17574 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
17577 this.toggle( false );
17578 e
.preventDefault();
17579 e
.stopPropagation();
17584 * Bind key down listener.
17588 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
17589 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler
);
17593 * Unbind key down listener.
17597 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
17598 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler
);
17602 * Show, hide, or toggle the visibility of the anchor.
17604 * @param {boolean} [show] Show anchor, omit to toggle
17606 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
17607 show
= show
=== undefined ? !this.anchored
: !!show
;
17609 if ( this.anchored
!== show
) {
17611 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
17613 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
17615 this.anchored
= show
;
17620 * Check if the anchor is visible.
17622 * @return {boolean} Anchor is visible
17624 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
17625 return this.anchor
;
17631 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
17633 show
= show
=== undefined ? !this.isVisible() : !!show
;
17635 change
= show
!== this.isVisible();
17638 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
17642 if ( this.autoClose
) {
17643 this.bindMouseDownListener();
17644 this.bindKeyDownListener();
17646 this.updateDimensions();
17647 this.toggleClipping( true );
17649 this.toggleClipping( false );
17650 if ( this.autoClose
) {
17651 this.unbindMouseDownListener();
17652 this.unbindKeyDownListener();
17661 * Set the size of the popup.
17663 * Changing the size may also change the popup's position depending on the alignment.
17665 * @param {number} width Width in pixels
17666 * @param {number} height Height in pixels
17667 * @param {boolean} [transition=false] Use a smooth transition
17670 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
17671 this.width
= width
;
17672 this.height
= height
!== undefined ? height
: null;
17673 if ( this.isVisible() ) {
17674 this.updateDimensions( transition
);
17679 * Update the size and position.
17681 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
17682 * be called automatically.
17684 * @param {boolean} [transition=false] Use a smooth transition
17687 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
17688 var popupOffset
, originOffset
, containerLeft
, containerWidth
, containerRight
,
17689 popupLeft
, popupRight
, overlapLeft
, overlapRight
, anchorWidth
,
17690 align
= this.align
,
17693 if ( !this.$container
) {
17694 // Lazy-initialize $container if not specified in constructor
17695 this.$container
= $( this.getClosestScrollableElementContainer() );
17698 // Set height and width before measuring things, since it might cause our measurements
17699 // to change (e.g. due to scrollbars appearing or disappearing)
17702 height
: this.height
!== null ? this.height
: 'auto'
17705 // If we are in RTL, we need to flip the alignment, unless it is center
17706 if ( align
=== 'forwards' || align
=== 'backwards' ) {
17707 if ( this.$container
.css( 'direction' ) === 'rtl' ) {
17708 align
= ( { forwards
: 'force-left', backwards
: 'force-right' } )[ this.align
];
17710 align
= ( { forwards
: 'force-right', backwards
: 'force-left' } )[ this.align
];
17715 // Compute initial popupOffset based on alignment
17716 popupOffset
= this.width
* ( { 'force-left': -1, center
: -0.5, 'force-right': 0 } )[ align
];
17718 // Figure out if this will cause the popup to go beyond the edge of the container
17719 originOffset
= this.$element
.offset().left
;
17720 containerLeft
= this.$container
.offset().left
;
17721 containerWidth
= this.$container
.innerWidth();
17722 containerRight
= containerLeft
+ containerWidth
;
17723 popupLeft
= popupOffset
- this.containerPadding
;
17724 popupRight
= popupOffset
+ this.containerPadding
+ this.width
+ this.containerPadding
;
17725 overlapLeft
= ( originOffset
+ popupLeft
) - containerLeft
;
17726 overlapRight
= containerRight
- ( originOffset
+ popupRight
);
17728 // Adjust offset to make the popup not go beyond the edge, if needed
17729 if ( overlapRight
< 0 ) {
17730 popupOffset
+= overlapRight
;
17731 } else if ( overlapLeft
< 0 ) {
17732 popupOffset
-= overlapLeft
;
17735 // Adjust offset to avoid anchor being rendered too close to the edge
17736 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
17737 // TODO: Find a measurement that works for CSS anchors and image anchors
17738 anchorWidth
= this.$anchor
[ 0 ].scrollWidth
* 2;
17739 if ( popupOffset
+ this.width
< anchorWidth
) {
17740 popupOffset
= anchorWidth
- this.width
;
17741 } else if ( -popupOffset
< anchorWidth
) {
17742 popupOffset
= -anchorWidth
;
17745 // Prevent transition from being interrupted
17746 clearTimeout( this.transitionTimeout
);
17747 if ( transition
) {
17748 // Enable transition
17749 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
17752 // Position body relative to anchor
17753 this.$popup
.css( 'margin-left', popupOffset
);
17755 if ( transition
) {
17756 // Prevent transitioning after transition is complete
17757 this.transitionTimeout
= setTimeout( function () {
17758 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
17761 // Prevent transitioning immediately
17762 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
17765 // Reevaluate clipping state since we've relocated and resized the popup
17772 * Set popup alignment
17773 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17774 * `backwards` or `forwards`.
17776 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
17777 // Validate alignment and transform deprecated values
17778 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
17779 this.align
= { left
: 'force-right', right
: 'force-left' }[ align
] || align
;
17781 this.align
= 'center';
17786 * Get popup alignment
17787 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17788 * `backwards` or `forwards`.
17790 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
17795 * Progress bars visually display the status of an operation, such as a download,
17796 * and can be either determinate or indeterminate:
17798 * - **determinate** process bars show the percent of an operation that is complete.
17800 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
17801 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
17802 * not use percentages.
17804 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
17807 * // Examples of determinate and indeterminate progress bars.
17808 * var progressBar1 = new OO.ui.ProgressBarWidget( {
17811 * var progressBar2 = new OO.ui.ProgressBarWidget();
17813 * // Create a FieldsetLayout to layout progress bars
17814 * var fieldset = new OO.ui.FieldsetLayout;
17815 * fieldset.addItems( [
17816 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
17817 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
17819 * $( 'body' ).append( fieldset.$element );
17822 * @extends OO.ui.Widget
17825 * @param {Object} [config] Configuration options
17826 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
17827 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
17828 * By default, the progress bar is indeterminate.
17830 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
17831 // Configuration initialization
17832 config
= config
|| {};
17834 // Parent constructor
17835 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
17838 this.$bar
= $( '<div>' );
17839 this.progress
= null;
17842 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
17843 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
17846 role
: 'progressbar',
17847 'aria-valuemin': 0,
17848 'aria-valuemax': 100
17850 .addClass( 'oo-ui-progressBarWidget' )
17851 .append( this.$bar
);
17856 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
17858 /* Static Properties */
17860 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
17865 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
17867 * @return {number|boolean} Progress percent
17869 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
17870 return this.progress
;
17874 * Set the percent of the process completed or `false` for an indeterminate process.
17876 * @param {number|boolean} progress Progress percent or `false` for indeterminate
17878 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
17879 this.progress
= progress
;
17881 if ( progress
!== false ) {
17882 this.$bar
.css( 'width', this.progress
+ '%' );
17883 this.$element
.attr( 'aria-valuenow', this.progress
);
17885 this.$bar
.css( 'width', '' );
17886 this.$element
.removeAttr( 'aria-valuenow' );
17888 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress
);
17892 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
17893 * and a menu of search results, which is displayed beneath the query
17894 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
17895 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
17896 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
17898 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
17899 * the [OOjs UI demos][1] for an example.
17901 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
17904 * @extends OO.ui.Widget
17907 * @param {Object} [config] Configuration options
17908 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
17909 * @cfg {string} [value] Initial query value
17911 OO
.ui
.SearchWidget
= function OoUiSearchWidget( config
) {
17912 // Configuration initialization
17913 config
= config
|| {};
17915 // Parent constructor
17916 OO
.ui
.SearchWidget
.parent
.call( this, config
);
17919 this.query
= new OO
.ui
.TextInputWidget( {
17921 placeholder
: config
.placeholder
,
17922 value
: config
.value
17924 this.results
= new OO
.ui
.SelectWidget();
17925 this.$query
= $( '<div>' );
17926 this.$results
= $( '<div>' );
17929 this.query
.connect( this, {
17930 change
: 'onQueryChange',
17931 enter
: 'onQueryEnter'
17933 this.query
.$input
.on( 'keydown', this.onQueryKeydown
.bind( this ) );
17937 .addClass( 'oo-ui-searchWidget-query' )
17938 .append( this.query
.$element
);
17940 .addClass( 'oo-ui-searchWidget-results' )
17941 .append( this.results
.$element
);
17943 .addClass( 'oo-ui-searchWidget' )
17944 .append( this.$results
, this.$query
);
17949 OO
.inheritClass( OO
.ui
.SearchWidget
, OO
.ui
.Widget
);
17954 * Handle query key down events.
17957 * @param {jQuery.Event} e Key down event
17959 OO
.ui
.SearchWidget
.prototype.onQueryKeydown = function ( e
) {
17960 var highlightedItem
, nextItem
,
17961 dir
= e
.which
=== OO
.ui
.Keys
.DOWN
? 1 : ( e
.which
=== OO
.ui
.Keys
.UP
? -1 : 0 );
17964 highlightedItem
= this.results
.getHighlightedItem();
17965 if ( !highlightedItem
) {
17966 highlightedItem
= this.results
.getSelectedItem();
17968 nextItem
= this.results
.getRelativeSelectableItem( highlightedItem
, dir
);
17969 this.results
.highlightItem( nextItem
);
17970 nextItem
.scrollElementIntoView();
17975 * Handle select widget select events.
17977 * Clears existing results. Subclasses should repopulate items according to new query.
17980 * @param {string} value New value
17982 OO
.ui
.SearchWidget
.prototype.onQueryChange = function () {
17984 this.results
.clearItems();
17988 * Handle select widget enter key events.
17990 * Chooses highlighted item.
17993 * @param {string} value New value
17995 OO
.ui
.SearchWidget
.prototype.onQueryEnter = function () {
17996 var highlightedItem
= this.results
.getHighlightedItem();
17997 if ( highlightedItem
) {
17998 this.results
.chooseItem( highlightedItem
);
18003 * Get the query input.
18005 * @return {OO.ui.TextInputWidget} Query input
18007 OO
.ui
.SearchWidget
.prototype.getQuery = function () {
18012 * Get the search results menu.
18014 * @return {OO.ui.SelectWidget} Menu of search results
18016 OO
.ui
.SearchWidget
.prototype.getResults = function () {
18017 return this.results
;
18021 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
18022 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
18023 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
18026 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
18027 * information, please see the [OOjs UI documentation on MediaWiki][1].
18030 * // Example of a select widget with three options
18031 * var select = new OO.ui.SelectWidget( {
18033 * new OO.ui.OptionWidget( {
18035 * label: 'Option One',
18037 * new OO.ui.OptionWidget( {
18039 * label: 'Option Two',
18041 * new OO.ui.OptionWidget( {
18043 * label: 'Option Three',
18047 * $( 'body' ).append( select.$element );
18049 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18053 * @extends OO.ui.Widget
18054 * @mixins OO.ui.mixin.GroupWidget
18057 * @param {Object} [config] Configuration options
18058 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
18059 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
18060 * the [OOjs UI documentation on MediaWiki] [2] for examples.
18061 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18063 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
18064 // Configuration initialization
18065 config
= config
|| {};
18067 // Parent constructor
18068 OO
.ui
.SelectWidget
.parent
.call( this, config
);
18070 // Mixin constructors
18071 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
18074 this.pressed
= false;
18075 this.selecting
= null;
18076 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
18077 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
18078 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
18079 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
18080 this.keyPressBuffer
= '';
18081 this.keyPressBufferTimer
= null;
18084 this.connect( this, {
18087 this.$element
.on( {
18088 mousedown
: this.onMouseDown
.bind( this ),
18089 mouseover
: this.onMouseOver
.bind( this ),
18090 mouseleave
: this.onMouseLeave
.bind( this )
18095 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
18096 .attr( 'role', 'listbox' );
18097 if ( Array
.isArray( config
.items
) ) {
18098 this.addItems( config
.items
);
18104 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
18106 // Need to mixin base class as well
18107 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupElement
);
18108 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
18111 OO
.ui
.SelectWidget
.static.passAllFilter = function () {
18120 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
18122 * @param {OO.ui.OptionWidget|null} item Highlighted item
18128 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
18129 * pressed state of an option.
18131 * @param {OO.ui.OptionWidget|null} item Pressed item
18137 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
18139 * @param {OO.ui.OptionWidget|null} item Selected item
18144 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
18145 * @param {OO.ui.OptionWidget} item Chosen item
18151 * An `add` event is emitted when options are added to the select with the #addItems method.
18153 * @param {OO.ui.OptionWidget[]} items Added items
18154 * @param {number} index Index of insertion point
18160 * A `remove` event is emitted when options are removed from the select with the #clearItems
18161 * or #removeItems methods.
18163 * @param {OO.ui.OptionWidget[]} items Removed items
18169 * Handle mouse down events.
18172 * @param {jQuery.Event} e Mouse down event
18174 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
18177 if ( !this.isDisabled() && e
.which
=== 1 ) {
18178 this.togglePressed( true );
18179 item
= this.getTargetItem( e
);
18180 if ( item
&& item
.isSelectable() ) {
18181 this.pressItem( item
);
18182 this.selecting
= item
;
18183 OO
.ui
.addCaptureEventListener(
18184 this.getElementDocument(),
18186 this.onMouseUpHandler
18188 OO
.ui
.addCaptureEventListener(
18189 this.getElementDocument(),
18191 this.onMouseMoveHandler
18199 * Handle mouse up events.
18202 * @param {jQuery.Event} e Mouse up event
18204 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
18207 this.togglePressed( false );
18208 if ( !this.selecting
) {
18209 item
= this.getTargetItem( e
);
18210 if ( item
&& item
.isSelectable() ) {
18211 this.selecting
= item
;
18214 if ( !this.isDisabled() && e
.which
=== 1 && this.selecting
) {
18215 this.pressItem( null );
18216 this.chooseItem( this.selecting
);
18217 this.selecting
= null;
18220 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup',
18221 this.onMouseUpHandler
);
18222 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mousemove',
18223 this.onMouseMoveHandler
);
18229 * Handle mouse move events.
18232 * @param {jQuery.Event} e Mouse move event
18234 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
18237 if ( !this.isDisabled() && this.pressed
) {
18238 item
= this.getTargetItem( e
);
18239 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
18240 this.pressItem( item
);
18241 this.selecting
= item
;
18248 * Handle mouse over events.
18251 * @param {jQuery.Event} e Mouse over event
18253 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
18256 if ( !this.isDisabled() ) {
18257 item
= this.getTargetItem( e
);
18258 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
18264 * Handle mouse leave events.
18267 * @param {jQuery.Event} e Mouse over event
18269 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
18270 if ( !this.isDisabled() ) {
18271 this.highlightItem( null );
18277 * Handle key down events.
18280 * @param {jQuery.Event} e Key down event
18282 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
18285 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
18287 if ( !this.isDisabled() && this.isVisible() ) {
18288 switch ( e
.keyCode
) {
18289 case OO
.ui
.Keys
.ENTER
:
18290 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
18291 // Was only highlighted, now let's select it. No-op if already selected.
18292 this.chooseItem( currentItem
);
18296 case OO
.ui
.Keys
.UP
:
18297 case OO
.ui
.Keys
.LEFT
:
18298 this.clearKeyPressBuffer();
18299 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
18302 case OO
.ui
.Keys
.DOWN
:
18303 case OO
.ui
.Keys
.RIGHT
:
18304 this.clearKeyPressBuffer();
18305 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
18308 case OO
.ui
.Keys
.ESCAPE
:
18309 case OO
.ui
.Keys
.TAB
:
18310 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
18311 currentItem
.setHighlighted( false );
18313 this.unbindKeyDownListener();
18314 this.unbindKeyPressListener();
18315 // Don't prevent tabbing away / defocusing
18321 if ( nextItem
.constructor.static.highlightable
) {
18322 this.highlightItem( nextItem
);
18324 this.chooseItem( nextItem
);
18326 nextItem
.scrollElementIntoView();
18330 // Can't just return false, because e is not always a jQuery event
18331 e
.preventDefault();
18332 e
.stopPropagation();
18338 * Bind key down listener.
18342 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
18343 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler
);
18347 * Unbind key down listener.
18351 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
18352 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler
);
18356 * Clear the key-press buffer
18360 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
18361 if ( this.keyPressBufferTimer
) {
18362 clearTimeout( this.keyPressBufferTimer
);
18363 this.keyPressBufferTimer
= null;
18365 this.keyPressBuffer
= '';
18369 * Handle key press events.
18372 * @param {jQuery.Event} e Key press event
18374 OO
.ui
.SelectWidget
.prototype.onKeyPress = function ( e
) {
18375 var c
, filter
, item
;
18377 if ( !e
.charCode
) {
18378 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
18379 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
18384 if ( String
.fromCodePoint
) {
18385 c
= String
.fromCodePoint( e
.charCode
);
18387 c
= String
.fromCharCode( e
.charCode
);
18390 if ( this.keyPressBufferTimer
) {
18391 clearTimeout( this.keyPressBufferTimer
);
18393 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
18395 item
= this.getHighlightedItem() || this.getSelectedItem();
18397 if ( this.keyPressBuffer
=== c
) {
18398 // Common (if weird) special case: typing "xxxx" will cycle through all
18399 // the items beginning with "x".
18401 item
= this.getRelativeSelectableItem( item
, 1 );
18404 this.keyPressBuffer
+= c
;
18407 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
18408 if ( !item
|| !filter( item
) ) {
18409 item
= this.getRelativeSelectableItem( item
, 1, filter
);
18412 if ( item
.constructor.static.highlightable
) {
18413 this.highlightItem( item
);
18415 this.chooseItem( item
);
18417 item
.scrollElementIntoView();
18424 * Get a matcher for the specific string
18427 * @param {string} s String to match against items
18428 * @param {boolean} [exact=false] Only accept exact matches
18429 * @return {Function} function ( OO.ui.OptionItem ) => boolean
18431 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
, exact
) {
18434 if ( s
.normalize
) {
18437 s
= exact
? s
.trim() : s
.replace( /^\s+/, '' );
18438 re
= '^\\s*' + s
.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
18442 re
= new RegExp( re
, 'i' );
18443 return function ( item
) {
18444 var l
= item
.getLabel();
18445 if ( typeof l
!== 'string' ) {
18446 l
= item
.$label
.text();
18448 if ( l
.normalize
) {
18451 return re
.test( l
);
18456 * Bind key press listener.
18460 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
18461 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler
);
18465 * Unbind key down listener.
18467 * If you override this, be sure to call this.clearKeyPressBuffer() from your
18472 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
18473 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler
);
18474 this.clearKeyPressBuffer();
18478 * Visibility change handler
18481 * @param {boolean} visible
18483 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
18485 this.clearKeyPressBuffer();
18490 * Get the closest item to a jQuery.Event.
18493 * @param {jQuery.Event} e
18494 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
18496 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
18497 return $( e
.target
).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
18501 * Get selected item.
18503 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
18505 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
18508 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18509 if ( this.items
[ i
].isSelected() ) {
18510 return this.items
[ i
];
18517 * Get highlighted item.
18519 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
18521 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
18524 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18525 if ( this.items
[ i
].isHighlighted() ) {
18526 return this.items
[ i
];
18533 * Toggle pressed state.
18535 * Press is a state that occurs when a user mouses down on an item, but
18536 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
18537 * until the user releases the mouse.
18539 * @param {boolean} pressed An option is being pressed
18541 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
18542 if ( pressed
=== undefined ) {
18543 pressed
= !this.pressed
;
18545 if ( pressed
!== this.pressed
) {
18547 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
18548 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
18549 this.pressed
= pressed
;
18554 * Highlight an option. If the `item` param is omitted, no options will be highlighted
18555 * and any existing highlight will be removed. The highlight is mutually exclusive.
18557 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
18561 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
18562 var i
, len
, highlighted
,
18565 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18566 highlighted
= this.items
[ i
] === item
;
18567 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
18568 this.items
[ i
].setHighlighted( highlighted
);
18573 this.emit( 'highlight', item
);
18580 * Fetch an item by its label.
18582 * @param {string} label Label of the item to select.
18583 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18584 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
18586 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
18587 var i
, item
, found
,
18588 len
= this.items
.length
,
18589 filter
= this.getItemMatcher( label
, true );
18591 for ( i
= 0; i
< len
; i
++ ) {
18592 item
= this.items
[ i
];
18593 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
18600 filter
= this.getItemMatcher( label
, false );
18601 for ( i
= 0; i
< len
; i
++ ) {
18602 item
= this.items
[ i
];
18603 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
18619 * Programmatically select an option by its label. If the item does not exist,
18620 * all options will be deselected.
18622 * @param {string} [label] Label of the item to select.
18623 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18627 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
18628 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
18629 if ( label
=== undefined || !itemFromLabel
) {
18630 return this.selectItem();
18632 return this.selectItem( itemFromLabel
);
18636 * Programmatically select an option by its data. If the `data` parameter is omitted,
18637 * or if the item does not exist, all options will be deselected.
18639 * @param {Object|string} [data] Value of the item to select, omit to deselect all
18643 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
18644 var itemFromData
= this.getItemFromData( data
);
18645 if ( data
=== undefined || !itemFromData
) {
18646 return this.selectItem();
18648 return this.selectItem( itemFromData
);
18652 * Programmatically select an option by its reference. If the `item` parameter is omitted,
18653 * all options will be deselected.
18655 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
18659 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
18660 var i
, len
, selected
,
18663 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18664 selected
= this.items
[ i
] === item
;
18665 if ( this.items
[ i
].isSelected() !== selected
) {
18666 this.items
[ i
].setSelected( selected
);
18671 this.emit( 'select', item
);
18680 * Press is a state that occurs when a user mouses down on an item, but has not
18681 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
18682 * releases the mouse.
18684 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
18688 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
18689 var i
, len
, pressed
,
18692 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18693 pressed
= this.items
[ i
] === item
;
18694 if ( this.items
[ i
].isPressed() !== pressed
) {
18695 this.items
[ i
].setPressed( pressed
);
18700 this.emit( 'press', item
);
18709 * Note that ‘choose’ should never be modified programmatically. A user can choose
18710 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
18711 * use the #selectItem method.
18713 * This method is identical to #selectItem, but may vary in subclasses that take additional action
18714 * when users choose an item with the keyboard or mouse.
18716 * @param {OO.ui.OptionWidget} item Item to choose
18720 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
18722 this.selectItem( item
);
18723 this.emit( 'choose', item
);
18730 * Get an option by its position relative to the specified item (or to the start of the option array,
18731 * if item is `null`). The direction in which to search through the option array is specified with a
18732 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
18733 * `null` if there are no options in the array.
18735 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
18736 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
18737 * @param {Function} filter Only consider items for which this function returns
18738 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
18739 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
18741 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
, filter
) {
18742 var currentIndex
, nextIndex
, i
,
18743 increase
= direction
> 0 ? 1 : -1,
18744 len
= this.items
.length
;
18746 if ( !$.isFunction( filter
) ) {
18747 filter
= OO
.ui
.SelectWidget
.static.passAllFilter
;
18750 if ( item
instanceof OO
.ui
.OptionWidget
) {
18751 currentIndex
= this.items
.indexOf( item
);
18752 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
18754 // If no item is selected and moving forward, start at the beginning.
18755 // If moving backward, start at the end.
18756 nextIndex
= direction
> 0 ? 0 : len
- 1;
18759 for ( i
= 0; i
< len
; i
++ ) {
18760 item
= this.items
[ nextIndex
];
18761 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
18764 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
18770 * Get the next selectable item or `null` if there are no selectable items.
18771 * Disabled options and menu-section markers and breaks are not selectable.
18773 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
18775 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
18778 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18779 item
= this.items
[ i
];
18780 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() ) {
18789 * Add an array of options to the select. Optionally, an index number can be used to
18790 * specify an insertion point.
18792 * @param {OO.ui.OptionWidget[]} items Items to add
18793 * @param {number} [index] Index to insert items after
18797 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
18799 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
18801 // Always provide an index, even if it was omitted
18802 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
18808 * Remove the specified array of options from the select. Options will be detached
18809 * from the DOM, not removed, so they can be reused later. To remove all options from
18810 * the select, you may wish to use the #clearItems method instead.
18812 * @param {OO.ui.OptionWidget[]} items Items to remove
18816 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
18819 // Deselect items being removed
18820 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
18822 if ( item
.isSelected() ) {
18823 this.selectItem( null );
18828 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
18830 this.emit( 'remove', items
);
18836 * Clear all options from the select. Options will be detached from the DOM, not removed,
18837 * so that they can be reused later. To remove a subset of options from the select, use
18838 * the #removeItems method.
18843 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
18844 var items
= this.items
.slice();
18847 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
18850 this.selectItem( null );
18852 this.emit( 'remove', items
);
18858 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
18859 * button options and is used together with
18860 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
18861 * highlighting, choosing, and selecting mutually exclusive options. Please see
18862 * the [OOjs UI documentation on MediaWiki] [1] for more information.
18865 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
18866 * var option1 = new OO.ui.ButtonOptionWidget( {
18868 * label: 'Option 1',
18869 * title: 'Button option 1'
18872 * var option2 = new OO.ui.ButtonOptionWidget( {
18874 * label: 'Option 2',
18875 * title: 'Button option 2'
18878 * var option3 = new OO.ui.ButtonOptionWidget( {
18880 * label: 'Option 3',
18881 * title: 'Button option 3'
18884 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
18885 * items: [ option1, option2, option3 ]
18887 * $( 'body' ).append( buttonSelect.$element );
18889 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18892 * @extends OO.ui.SelectWidget
18893 * @mixins OO.ui.mixin.TabIndexedElement
18896 * @param {Object} [config] Configuration options
18898 OO
.ui
.ButtonSelectWidget
= function OoUiButtonSelectWidget( config
) {
18899 // Parent constructor
18900 OO
.ui
.ButtonSelectWidget
.parent
.call( this, config
);
18902 // Mixin constructors
18903 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
18906 this.$element
.on( {
18907 focus
: this.bindKeyDownListener
.bind( this ),
18908 blur
: this.unbindKeyDownListener
.bind( this )
18912 this.$element
.addClass( 'oo-ui-buttonSelectWidget' );
18917 OO
.inheritClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.SelectWidget
);
18918 OO
.mixinClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
18921 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
18922 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
18923 * an interface for adding, removing and selecting options.
18924 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18926 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
18927 * OO.ui.RadioSelectInputWidget instead.
18930 * // A RadioSelectWidget with RadioOptions.
18931 * var option1 = new OO.ui.RadioOptionWidget( {
18933 * label: 'Selected radio option'
18936 * var option2 = new OO.ui.RadioOptionWidget( {
18938 * label: 'Unselected radio option'
18941 * var radioSelect=new OO.ui.RadioSelectWidget( {
18942 * items: [ option1, option2 ]
18945 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
18946 * radioSelect.selectItem( option1 );
18948 * $( 'body' ).append( radioSelect.$element );
18950 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18954 * @extends OO.ui.SelectWidget
18955 * @mixins OO.ui.mixin.TabIndexedElement
18958 * @param {Object} [config] Configuration options
18960 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
18961 // Parent constructor
18962 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
18964 // Mixin constructors
18965 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
18968 this.$element
.on( {
18969 focus
: this.bindKeyDownListener
.bind( this ),
18970 blur
: this.unbindKeyDownListener
.bind( this )
18975 .addClass( 'oo-ui-radioSelectWidget' )
18976 .attr( 'role', 'radiogroup' );
18981 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
18982 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
18985 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
18986 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
18987 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
18988 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
18989 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
18990 * and customized to be opened, closed, and displayed as needed.
18992 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
18993 * mouse outside the menu.
18995 * Menus also have support for keyboard interaction:
18997 * - Enter/Return key: choose and select a menu option
18998 * - Up-arrow key: highlight the previous menu option
18999 * - Down-arrow key: highlight the next menu option
19000 * - Esc key: hide the menu
19002 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
19003 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
19006 * @extends OO.ui.SelectWidget
19007 * @mixins OO.ui.mixin.ClippableElement
19010 * @param {Object} [config] Configuration options
19011 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
19012 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
19013 * and {@link OO.ui.mixin.LookupElement LookupElement}
19014 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
19015 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiSelectWidget CapsuleMultiSelectWidget}
19016 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
19017 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
19018 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
19019 * that button, unless the button (or its parent widget) is passed in here.
19020 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
19021 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
19023 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
19024 // Configuration initialization
19025 config
= config
|| {};
19027 // Parent constructor
19028 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
19030 // Mixin constructors
19031 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
19034 this.newItems
= null;
19035 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
19036 this.filterFromInput
= !!config
.filterFromInput
;
19037 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
19038 this.$widget
= config
.widget
? config
.widget
.$element
: null;
19039 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
19040 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
19044 .addClass( 'oo-ui-menuSelectWidget' )
19045 .attr( 'role', 'menu' );
19047 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
19048 // that reference properties not initialized at that time of parent class construction
19049 // TODO: Find a better way to handle post-constructor setup
19050 this.visible
= false;
19051 this.$element
.addClass( 'oo-ui-element-hidden' );
19056 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
19057 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
19062 * Handles document mouse down events.
19065 * @param {jQuery.Event} e Key down event
19067 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
19069 !OO
.ui
.contains( this.$element
[ 0 ], e
.target
, true ) &&
19070 ( !this.$widget
|| !OO
.ui
.contains( this.$widget
[ 0 ], e
.target
, true ) )
19072 this.toggle( false );
19079 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
19080 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
19082 if ( !this.isDisabled() && this.isVisible() ) {
19083 switch ( e
.keyCode
) {
19084 case OO
.ui
.Keys
.LEFT
:
19085 case OO
.ui
.Keys
.RIGHT
:
19086 // Do nothing if a text field is associated, arrow keys will be handled natively
19087 if ( !this.$input
) {
19088 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
19091 case OO
.ui
.Keys
.ESCAPE
:
19092 case OO
.ui
.Keys
.TAB
:
19093 if ( currentItem
) {
19094 currentItem
.setHighlighted( false );
19096 this.toggle( false );
19097 // Don't prevent tabbing away, prevent defocusing
19098 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
19099 e
.preventDefault();
19100 e
.stopPropagation();
19104 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
19111 * Update menu item visibility after input changes.
19114 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
19116 len
= this.items
.length
,
19117 showAll
= !this.isVisible(),
19118 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() );
19120 for ( i
= 0; i
< len
; i
++ ) {
19121 item
= this.items
[ i
];
19122 if ( item
instanceof OO
.ui
.OptionWidget
) {
19123 item
.toggle( showAll
|| filter( item
) );
19127 // Reevaluate clipping
19134 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
19135 if ( this.$input
) {
19136 this.$input
.on( 'keydown', this.onKeyDownHandler
);
19138 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyDownListener
.call( this );
19145 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
19146 if ( this.$input
) {
19147 this.$input
.off( 'keydown', this.onKeyDownHandler
);
19149 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyDownListener
.call( this );
19156 OO
.ui
.MenuSelectWidget
.prototype.bindKeyPressListener = function () {
19157 if ( this.$input
) {
19158 if ( this.filterFromInput
) {
19159 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
19162 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyPressListener
.call( this );
19169 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyPressListener = function () {
19170 if ( this.$input
) {
19171 if ( this.filterFromInput
) {
19172 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
19173 this.updateItemVisibility();
19176 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyPressListener
.call( this );
19183 * When a user chooses an item, the menu is closed.
19185 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
19186 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
19187 * @param {OO.ui.OptionWidget} item Item to choose
19190 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
19191 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
19192 this.toggle( false );
19199 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
19203 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
19206 if ( !this.newItems
) {
19207 this.newItems
= [];
19210 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
19212 if ( this.isVisible() ) {
19213 // Defer fitting label until item has been attached
19216 this.newItems
.push( item
);
19220 // Reevaluate clipping
19229 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
19231 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
19233 // Reevaluate clipping
19242 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
19244 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
19246 // Reevaluate clipping
19255 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
19256 var i
, len
, change
;
19258 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
19259 change
= visible
!== this.isVisible();
19262 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
19266 this.bindKeyDownListener();
19267 this.bindKeyPressListener();
19269 if ( this.newItems
&& this.newItems
.length
) {
19270 for ( i
= 0, len
= this.newItems
.length
; i
< len
; i
++ ) {
19271 this.newItems
[ i
].fitLabel();
19273 this.newItems
= null;
19275 this.toggleClipping( true );
19278 if ( this.autoHide
) {
19279 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler
);
19282 this.unbindKeyDownListener();
19283 this.unbindKeyPressListener();
19284 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler
);
19285 this.toggleClipping( false );
19293 * FloatingMenuSelectWidget is a menu that will stick under a specified
19294 * container, even when it is inserted elsewhere in the document (for example,
19295 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
19296 * menu from being clipped too aggresively.
19298 * The menu's position is automatically calculated and maintained when the menu
19299 * is toggled or the window is resized.
19301 * See OO.ui.ComboBoxInputWidget for an example of a widget that uses this class.
19304 * @extends OO.ui.MenuSelectWidget
19305 * @mixins OO.ui.mixin.FloatableElement
19308 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
19309 * Deprecated, omit this parameter and specify `$container` instead.
19310 * @param {Object} [config] Configuration options
19311 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
19313 OO
.ui
.FloatingMenuSelectWidget
= function OoUiFloatingMenuSelectWidget( inputWidget
, config
) {
19314 // Allow 'inputWidget' parameter and config for backwards compatibility
19315 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
19316 config
= inputWidget
;
19317 inputWidget
= config
.inputWidget
;
19320 // Configuration initialization
19321 config
= config
|| {};
19323 // Parent constructor
19324 OO
.ui
.FloatingMenuSelectWidget
.parent
.call( this, config
);
19326 // Properties (must be set before mixin constructors)
19327 this.inputWidget
= inputWidget
; // For backwards compatibility
19328 this.$container
= config
.$container
|| this.inputWidget
.$element
;
19330 // Mixins constructors
19331 OO
.ui
.mixin
.FloatableElement
.call( this, $.extend( {}, config
, { $floatableContainer
: this.$container
} ) );
19334 this.$element
.addClass( 'oo-ui-floatingMenuSelectWidget' );
19335 // For backwards compatibility
19336 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
19341 OO
.inheritClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
19342 OO
.mixinClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.mixin
.FloatableElement
);
19344 // For backwards compatibility
19345 OO
.ui
.TextInputMenuSelectWidget
= OO
.ui
.FloatingMenuSelectWidget
;
19352 OO
.ui
.FloatingMenuSelectWidget
.prototype.toggle = function ( visible
) {
19354 visible
= visible
=== undefined ? !this.isVisible() : !!visible
;
19355 change
= visible
!== this.isVisible();
19357 if ( change
&& visible
) {
19358 // Make sure the width is set before the parent method runs.
19359 this.setIdealSize( this.$container
.width() );
19363 // This will call this.clip(), which is nonsensical since we're not positioned yet...
19364 OO
.ui
.FloatingMenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
19367 this.togglePositioning( this.isVisible() );
19374 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
19375 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
19377 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
19380 * @extends OO.ui.SelectWidget
19381 * @mixins OO.ui.mixin.TabIndexedElement
19384 * @param {Object} [config] Configuration options
19386 OO
.ui
.OutlineSelectWidget
= function OoUiOutlineSelectWidget( config
) {
19387 // Parent constructor
19388 OO
.ui
.OutlineSelectWidget
.parent
.call( this, config
);
19390 // Mixin constructors
19391 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
19394 this.$element
.on( {
19395 focus
: this.bindKeyDownListener
.bind( this ),
19396 blur
: this.unbindKeyDownListener
.bind( this )
19400 this.$element
.addClass( 'oo-ui-outlineSelectWidget' );
19405 OO
.inheritClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.SelectWidget
);
19406 OO
.mixinClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
19409 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
19411 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
19414 * @extends OO.ui.SelectWidget
19415 * @mixins OO.ui.mixin.TabIndexedElement
19418 * @param {Object} [config] Configuration options
19420 OO
.ui
.TabSelectWidget
= function OoUiTabSelectWidget( config
) {
19421 // Parent constructor
19422 OO
.ui
.TabSelectWidget
.parent
.call( this, config
);
19424 // Mixin constructors
19425 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
19428 this.$element
.on( {
19429 focus
: this.bindKeyDownListener
.bind( this ),
19430 blur
: this.unbindKeyDownListener
.bind( this )
19434 this.$element
.addClass( 'oo-ui-tabSelectWidget' );
19439 OO
.inheritClass( OO
.ui
.TabSelectWidget
, OO
.ui
.SelectWidget
);
19440 OO
.mixinClass( OO
.ui
.TabSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
19443 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
19444 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
19445 * (to adjust the value in increments) to allow the user to enter a number.
19448 * // Example: A NumberInputWidget.
19449 * var numberInput = new OO.ui.NumberInputWidget( {
19450 * label: 'NumberInputWidget',
19451 * input: { value: 5, min: 1, max: 10 }
19453 * $( 'body' ).append( numberInput.$element );
19456 * @extends OO.ui.Widget
19459 * @param {Object} [config] Configuration options
19460 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
19461 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
19462 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
19463 * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
19464 * @cfg {number} [min=-Infinity] Minimum allowed value
19465 * @cfg {number} [max=Infinity] Maximum allowed value
19466 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
19467 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
19469 OO
.ui
.NumberInputWidget
= function OoUiNumberInputWidget( config
) {
19470 // Configuration initialization
19471 config
= $.extend( {
19479 // Parent constructor
19480 OO
.ui
.NumberInputWidget
.parent
.call( this, config
);
19483 this.input
= new OO
.ui
.TextInputWidget( $.extend(
19485 disabled
: this.isDisabled()
19489 this.minusButton
= new OO
.ui
.ButtonWidget( $.extend(
19491 disabled
: this.isDisabled(),
19494 config
.minusButton
,
19496 classes
: [ 'oo-ui-numberInputWidget-minusButton' ],
19500 this.plusButton
= new OO
.ui
.ButtonWidget( $.extend(
19502 disabled
: this.isDisabled(),
19507 classes
: [ 'oo-ui-numberInputWidget-plusButton' ],
19513 this.input
.connect( this, {
19514 change
: this.emit
.bind( this, 'change' ),
19515 enter
: this.emit
.bind( this, 'enter' )
19517 this.input
.$input
.on( {
19518 keydown
: this.onKeyDown
.bind( this ),
19519 'wheel mousewheel DOMMouseScroll': this.onWheel
.bind( this )
19521 this.plusButton
.connect( this, {
19522 click
: [ 'onButtonClick', +1 ]
19524 this.minusButton
.connect( this, {
19525 click
: [ 'onButtonClick', -1 ]
19529 this.setIsInteger( !!config
.isInteger
);
19530 this.setRange( config
.min
, config
.max
);
19531 this.setStep( config
.step
, config
.pageStep
);
19533 this.$field
= $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
19535 this.minusButton
.$element
,
19536 this.input
.$element
,
19537 this.plusButton
.$element
19539 this.$element
.addClass( 'oo-ui-numberInputWidget' ).append( this.$field
);
19540 this.input
.setValidation( this.validateNumber
.bind( this ) );
19545 OO
.inheritClass( OO
.ui
.NumberInputWidget
, OO
.ui
.Widget
);
19550 * A `change` event is emitted when the value of the input changes.
19556 * An `enter` event is emitted when the user presses 'enter' inside the text box.
19564 * Set whether only integers are allowed
19565 * @param {boolean} flag
19567 OO
.ui
.NumberInputWidget
.prototype.setIsInteger = function ( flag
) {
19568 this.isInteger
= !!flag
;
19569 this.input
.setValidityFlag();
19573 * Get whether only integers are allowed
19574 * @return {boolean} Flag value
19576 OO
.ui
.NumberInputWidget
.prototype.getIsInteger = function () {
19577 return this.isInteger
;
19581 * Set the range of allowed values
19582 * @param {number} min Minimum allowed value
19583 * @param {number} max Maximum allowed value
19585 OO
.ui
.NumberInputWidget
.prototype.setRange = function ( min
, max
) {
19587 throw new Error( 'Minimum (' + min
+ ') must not be greater than maximum (' + max
+ ')' );
19591 this.input
.setValidityFlag();
19595 * Get the current range
19596 * @return {number[]} Minimum and maximum values
19598 OO
.ui
.NumberInputWidget
.prototype.getRange = function () {
19599 return [ this.min
, this.max
];
19603 * Set the stepping deltas
19604 * @param {number} step Normal step
19605 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
19607 OO
.ui
.NumberInputWidget
.prototype.setStep = function ( step
, pageStep
) {
19609 throw new Error( 'Step value must be positive' );
19611 if ( pageStep
=== null ) {
19612 pageStep
= step
* 10;
19613 } else if ( pageStep
<= 0 ) {
19614 throw new Error( 'Page step value must be positive' );
19617 this.pageStep
= pageStep
;
19621 * Get the current stepping values
19622 * @return {number[]} Step and page step
19624 OO
.ui
.NumberInputWidget
.prototype.getStep = function () {
19625 return [ this.step
, this.pageStep
];
19629 * Get the current value of the widget
19632 OO
.ui
.NumberInputWidget
.prototype.getValue = function () {
19633 return this.input
.getValue();
19637 * Get the current value of the widget as a number
19638 * @return {number} May be NaN, or an invalid number
19640 OO
.ui
.NumberInputWidget
.prototype.getNumericValue = function () {
19641 return +this.input
.getValue();
19645 * Set the value of the widget
19646 * @param {string} value Invalid values are allowed
19648 OO
.ui
.NumberInputWidget
.prototype.setValue = function ( value
) {
19649 this.input
.setValue( value
);
19653 * Adjust the value of the widget
19654 * @param {number} delta Adjustment amount
19656 OO
.ui
.NumberInputWidget
.prototype.adjustValue = function ( delta
) {
19657 var n
, v
= this.getNumericValue();
19660 if ( isNaN( delta
) || !isFinite( delta
) ) {
19661 throw new Error( 'Delta must be a finite number' );
19664 if ( isNaN( v
) ) {
19668 n
= Math
.max( Math
.min( n
, this.max
), this.min
);
19669 if ( this.isInteger
) {
19670 n
= Math
.round( n
);
19675 this.setValue( n
);
19682 * @param {string} value Field value
19683 * @return {boolean}
19685 OO
.ui
.NumberInputWidget
.prototype.validateNumber = function ( value
) {
19687 if ( isNaN( n
) || !isFinite( n
) ) {
19691 /*jshint bitwise: false */
19692 if ( this.isInteger
&& ( n
| 0 ) !== n
) {
19695 /*jshint bitwise: true */
19697 if ( n
< this.min
|| n
> this.max
) {
19705 * Handle mouse click events.
19708 * @param {number} dir +1 or -1
19710 OO
.ui
.NumberInputWidget
.prototype.onButtonClick = function ( dir
) {
19711 this.adjustValue( dir
* this.step
);
19715 * Handle mouse wheel events.
19718 * @param {jQuery.Event} event
19720 OO
.ui
.NumberInputWidget
.prototype.onWheel = function ( event
) {
19723 // Standard 'wheel' event
19724 if ( event
.originalEvent
.deltaMode
!== undefined ) {
19725 this.sawWheelEvent
= true;
19727 if ( event
.originalEvent
.deltaY
) {
19728 delta
= -event
.originalEvent
.deltaY
;
19729 } else if ( event
.originalEvent
.deltaX
) {
19730 delta
= event
.originalEvent
.deltaX
;
19733 // Non-standard events
19734 if ( !this.sawWheelEvent
) {
19735 if ( event
.originalEvent
.wheelDeltaX
) {
19736 delta
= -event
.originalEvent
.wheelDeltaX
;
19737 } else if ( event
.originalEvent
.wheelDeltaY
) {
19738 delta
= event
.originalEvent
.wheelDeltaY
;
19739 } else if ( event
.originalEvent
.wheelDelta
) {
19740 delta
= event
.originalEvent
.wheelDelta
;
19741 } else if ( event
.originalEvent
.detail
) {
19742 delta
= -event
.originalEvent
.detail
;
19747 delta
= delta
< 0 ? -1 : 1;
19748 this.adjustValue( delta
* this.step
);
19755 * Handle key down events.
19758 * @param {jQuery.Event} e Key down event
19760 OO
.ui
.NumberInputWidget
.prototype.onKeyDown = function ( e
) {
19761 if ( !this.isDisabled() ) {
19762 switch ( e
.which
) {
19763 case OO
.ui
.Keys
.UP
:
19764 this.adjustValue( this.step
);
19766 case OO
.ui
.Keys
.DOWN
:
19767 this.adjustValue( -this.step
);
19769 case OO
.ui
.Keys
.PAGEUP
:
19770 this.adjustValue( this.pageStep
);
19772 case OO
.ui
.Keys
.PAGEDOWN
:
19773 this.adjustValue( -this.pageStep
);
19782 OO
.ui
.NumberInputWidget
.prototype.setDisabled = function ( disabled
) {
19784 OO
.ui
.NumberInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
19786 if ( this.input
) {
19787 this.input
.setDisabled( this.isDisabled() );
19789 if ( this.minusButton
) {
19790 this.minusButton
.setDisabled( this.isDisabled() );
19792 if ( this.plusButton
) {
19793 this.plusButton
.setDisabled( this.isDisabled() );
19800 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
19801 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
19802 * visually by a slider in the leftmost position.
19805 * // Toggle switches in the 'off' and 'on' position.
19806 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
19807 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
19811 * // Create a FieldsetLayout to layout and label switches
19812 * var fieldset = new OO.ui.FieldsetLayout( {
19813 * label: 'Toggle switches'
19815 * fieldset.addItems( [
19816 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
19817 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
19819 * $( 'body' ).append( fieldset.$element );
19822 * @extends OO.ui.ToggleWidget
19823 * @mixins OO.ui.mixin.TabIndexedElement
19826 * @param {Object} [config] Configuration options
19827 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
19828 * By default, the toggle switch is in the 'off' position.
19830 OO
.ui
.ToggleSwitchWidget
= function OoUiToggleSwitchWidget( config
) {
19831 // Parent constructor
19832 OO
.ui
.ToggleSwitchWidget
.parent
.call( this, config
);
19834 // Mixin constructors
19835 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
19838 this.dragging
= false;
19839 this.dragStart
= null;
19840 this.sliding
= false;
19841 this.$glow
= $( '<span>' );
19842 this.$grip
= $( '<span>' );
19845 this.$element
.on( {
19846 click
: this.onClick
.bind( this ),
19847 keypress
: this.onKeyPress
.bind( this )
19851 this.$glow
.addClass( 'oo-ui-toggleSwitchWidget-glow' );
19852 this.$grip
.addClass( 'oo-ui-toggleSwitchWidget-grip' );
19854 .addClass( 'oo-ui-toggleSwitchWidget' )
19855 .attr( 'role', 'checkbox' )
19856 .append( this.$glow
, this.$grip
);
19861 OO
.inheritClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.ToggleWidget
);
19862 OO
.mixinClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.mixin
.TabIndexedElement
);
19867 * Handle mouse click events.
19870 * @param {jQuery.Event} e Mouse click event
19872 OO
.ui
.ToggleSwitchWidget
.prototype.onClick = function ( e
) {
19873 if ( !this.isDisabled() && e
.which
=== 1 ) {
19874 this.setValue( !this.value
);
19880 * Handle key press events.
19883 * @param {jQuery.Event} e Key press event
19885 OO
.ui
.ToggleSwitchWidget
.prototype.onKeyPress = function ( e
) {
19886 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
19887 this.setValue( !this.value
);