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-25T01:06:47Z
16 * Namespace for all classes, static methods and static properties.
53 * Generate a unique ID for element
55 * @return {String} [id]
57 OO
.ui
.generateElementId = function () {
59 return 'oojsui-' + OO
.ui
.elementId
;
63 * Check if an element is focusable.
64 * Inspired from :focusable in jQueryUI v1.11.4 - 2015-04-14
66 * @param {jQuery} element Element to test
69 OO
.ui
.isFocusableElement = function ( $element
) {
71 element
= $element
[ 0 ];
73 // Anything disabled is not focusable
74 if ( element
.disabled
) {
78 // Check if the element is visible
80 // This is quicker than calling $element.is( ':visible' )
81 $.expr
.filters
.visible( element
) &&
82 // Check that all parents are visible
83 !$element
.parents().addBack().filter( function () {
84 return $.css( this, 'visibility' ) === 'hidden';
90 // Check if the element is ContentEditable, which is the string 'true'
91 if ( element
.contentEditable
=== 'true' ) {
95 // Anything with a non-negative numeric tabIndex is focusable.
96 // Use .prop to avoid browser bugs
97 if ( $element
.prop( 'tabIndex' ) >= 0 ) {
101 // Some element types are naturally focusable
102 // (indexOf is much faster than regex in Chrome and about the
103 // same in FF: https://jsperf.com/regex-vs-indexof-array2)
104 nodeName
= element
.nodeName
.toLowerCase();
105 if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName
) !== -1 ) {
109 // Links and areas are focusable if they have an href
110 if ( ( nodeName
=== 'a' || nodeName
=== 'area' ) && $element
.attr( 'href' ) !== undefined ) {
118 * Find a focusable child
120 * @param {jQuery} $container Container to search in
121 * @param {boolean} [backwards] Search backwards
122 * @return {jQuery} Focusable child, an empty jQuery object if none found
124 OO
.ui
.findFocusable = function ( $container
, backwards
) {
125 var $focusable
= $( [] ),
126 // $focusableCandidates is a superset of things that
127 // could get matched by isFocusableElement
128 $focusableCandidates
= $container
129 .find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' );
132 $focusableCandidates
= Array
.prototype.reverse
.call( $focusableCandidates
);
135 $focusableCandidates
.each( function () {
136 var $this = $( this );
137 if ( OO
.ui
.isFocusableElement( $this ) ) {
146 * Get the user's language and any fallback languages.
148 * These language codes are used to localize user interface elements in the user's language.
150 * In environments that provide a localization system, this function should be overridden to
151 * return the user's language(s). The default implementation returns English (en) only.
153 * @return {string[]} Language codes, in descending order of priority
155 OO
.ui
.getUserLanguages = function () {
160 * Get a value in an object keyed by language code.
162 * @param {Object.<string,Mixed>} obj Object keyed by language code
163 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
164 * @param {string} [fallback] Fallback code, used if no matching language can be found
165 * @return {Mixed} Local value
167 OO
.ui
.getLocalValue = function ( obj
, lang
, fallback
) {
170 // Requested language
174 // Known user language
175 langs
= OO
.ui
.getUserLanguages();
176 for ( i
= 0, len
= langs
.length
; i
< len
; i
++ ) {
183 if ( obj
[ fallback
] ) {
184 return obj
[ fallback
];
186 // First existing language
187 for ( lang
in obj
) {
195 * Check if a node is contained within another node
197 * Similar to jQuery#contains except a list of containers can be supplied
198 * and a boolean argument allows you to include the container in the match list
200 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
201 * @param {HTMLElement} contained Node to find
202 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
203 * @return {boolean} The node is in the list of target nodes
205 OO
.ui
.contains = function ( containers
, contained
, matchContainers
) {
207 if ( !Array
.isArray( containers
) ) {
208 containers
= [ containers
];
210 for ( i
= containers
.length
- 1; i
>= 0; i
-- ) {
211 if ( ( matchContainers
&& contained
=== containers
[ i
] ) || $.contains( containers
[ i
], contained
) ) {
219 * Return a function, that, as long as it continues to be invoked, will not
220 * be triggered. The function will be called after it stops being called for
221 * N milliseconds. If `immediate` is passed, trigger the function on the
222 * leading edge, instead of the trailing.
224 * Ported from: http://underscorejs.org/underscore.js
226 * @param {Function} func
227 * @param {number} wait
228 * @param {boolean} immediate
231 OO
.ui
.debounce = function ( func
, wait
, immediate
) {
236 later = function () {
239 func
.apply( context
, args
);
242 if ( immediate
&& !timeout
) {
243 func
.apply( context
, args
);
245 clearTimeout( timeout
);
246 timeout
= setTimeout( later
, wait
);
251 * Proxy for `node.addEventListener( eventName, handler, true )`, if the browser supports it.
252 * Otherwise falls back to non-capturing event listeners.
254 * @param {HTMLElement} node
255 * @param {string} eventName
256 * @param {Function} handler
258 OO
.ui
.addCaptureEventListener = function ( node
, eventName
, handler
) {
259 if ( node
.addEventListener
) {
260 node
.addEventListener( eventName
, handler
, true );
262 node
.attachEvent( 'on' + eventName
, handler
);
267 * Proxy for `node.removeEventListener( eventName, handler, true )`, if the browser supports it.
268 * Otherwise falls back to non-capturing event listeners.
270 * @param {HTMLElement} node
271 * @param {string} eventName
272 * @param {Function} handler
274 OO
.ui
.removeCaptureEventListener = function ( node
, eventName
, handler
) {
275 if ( node
.addEventListener
) {
276 node
.removeEventListener( eventName
, handler
, true );
278 node
.detachEvent( 'on' + eventName
, handler
);
283 * Reconstitute a JavaScript object corresponding to a widget created by
284 * the PHP implementation.
286 * This is an alias for `OO.ui.Element.static.infuse()`.
288 * @param {string|HTMLElement|jQuery} idOrNode
289 * A DOM id (if a string) or node for the widget to infuse.
290 * @return {OO.ui.Element}
291 * The `OO.ui.Element` corresponding to this (infusable) document node.
293 OO
.ui
.infuse = function ( idOrNode
) {
294 return OO
.ui
.Element
.static.infuse( idOrNode
);
299 * Message store for the default implementation of OO.ui.msg
301 * Environments that provide a localization system should not use this, but should override
302 * OO.ui.msg altogether.
307 // Tool tip for a button that moves items in a list down one place
308 'ooui-outline-control-move-down': 'Move item down',
309 // Tool tip for a button that moves items in a list up one place
310 'ooui-outline-control-move-up': 'Move item up',
311 // Tool tip for a button that removes items from a list
312 'ooui-outline-control-remove': 'Remove item',
313 // Label for the toolbar group that contains a list of all other available tools
314 'ooui-toolbar-more': 'More',
315 // Label for the fake tool that expands the full list of tools in a toolbar group
316 'ooui-toolgroup-expand': 'More',
317 // Label for the fake tool that collapses the full list of tools in a toolbar group
318 'ooui-toolgroup-collapse': 'Fewer',
319 // Default label for the accept button of a confirmation dialog
320 'ooui-dialog-message-accept': 'OK',
321 // Default label for the reject button of a confirmation dialog
322 'ooui-dialog-message-reject': 'Cancel',
323 // Title for process dialog error description
324 'ooui-dialog-process-error': 'Something went wrong',
325 // Label for process dialog dismiss error button, visible when describing errors
326 'ooui-dialog-process-dismiss': 'Dismiss',
327 // Label for process dialog retry action button, visible when describing only recoverable errors
328 'ooui-dialog-process-retry': 'Try again',
329 // Label for process dialog retry action button, visible when describing only warnings
330 'ooui-dialog-process-continue': 'Continue',
331 // Label for the file selection widget's select file button
332 'ooui-selectfile-button-select': 'Select a file',
333 // Label for the file selection widget if file selection is not supported
334 'ooui-selectfile-not-supported': 'File selection is not supported',
335 // Label for the file selection widget when no file is currently selected
336 'ooui-selectfile-placeholder': 'No file is selected',
337 // Label for the file selection widget's drop target
338 'ooui-selectfile-dragdrop-placeholder': 'Drop file here'
342 * Get a localized message.
344 * In environments that provide a localization system, this function should be overridden to
345 * return the message translated in the user's language. The default implementation always returns
348 * After the message key, message parameters may optionally be passed. In the default implementation,
349 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
350 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
351 * they support unnamed, ordered message parameters.
353 * @param {string} key Message key
354 * @param {Mixed...} [params] Message parameters
355 * @return {string} Translated message with parameters substituted
357 OO
.ui
.msg = function ( key
) {
358 var message
= messages
[ key
],
359 params
= Array
.prototype.slice
.call( arguments
, 1 );
360 if ( typeof message
=== 'string' ) {
361 // Perform $1 substitution
362 message
= message
.replace( /\$(\d+)/g, function ( unused
, n
) {
363 var i
= parseInt( n
, 10 );
364 return params
[ i
- 1 ] !== undefined ? params
[ i
- 1 ] : '$' + n
;
367 // Return placeholder if message not found
368 message
= '[' + key
+ ']';
374 * Package a message and arguments for deferred resolution.
376 * Use this when you are statically specifying a message and the message may not yet be present.
378 * @param {string} key Message key
379 * @param {Mixed...} [params] Message parameters
380 * @return {Function} Function that returns the resolved message when executed
382 OO
.ui
.deferMsg = function () {
383 var args
= arguments
;
385 return OO
.ui
.msg
.apply( OO
.ui
, args
);
392 * If the message is a function it will be executed, otherwise it will pass through directly.
394 * @param {Function|string} msg Deferred message, or message text
395 * @return {string} Resolved message
397 OO
.ui
.resolveMsg = function ( msg
) {
398 if ( $.isFunction( msg
) ) {
405 * @param {string} url
408 OO
.ui
.isSafeUrl = function ( url
) {
410 // Keep in sync with php/Tag.php
412 'bitcoin:', 'ftp:', 'ftps:', 'geo:', 'git:', 'gopher:', 'http:', 'https:', 'irc:', 'ircs:',
413 'magnet:', 'mailto:', 'mms:', 'news:', 'nntp:', 'redis:', 'sftp:', 'sip:', 'sips:', 'sms:', 'ssh:',
414 'svn:', 'tel:', 'telnet:', 'urn:', 'worldwind:', 'xmpp:'
417 if ( url
.indexOf( ':' ) === -1 ) {
422 protocol
= url
.split( ':', 1 )[ 0 ] + ':';
423 if ( !protocol
.match( /^([A-za-z0-9\+\.\-])+:/ ) ) {
424 // Not a valid protocol, safe
428 // Safe if in the whitelist
429 return whitelist
.indexOf( protocol
) !== -1;
439 * Namespace for OOjs UI mixins.
441 * Mixins are named according to the type of object they are intended to
442 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
443 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
444 * is intended to be mixed in to an instance of OO.ui.Widget.
452 * PendingElement is a mixin that is used to create elements that notify users that something is happening
453 * and that they should wait before proceeding. The pending state is visually represented with a pending
454 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
455 * field of a {@link OO.ui.TextInputWidget text input widget}.
457 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
458 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
459 * in process dialogs.
462 * function MessageDialog( config ) {
463 * MessageDialog.parent.call( this, config );
465 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
467 * MessageDialog.static.actions = [
468 * { action: 'save', label: 'Done', flags: 'primary' },
469 * { label: 'Cancel', flags: 'safe' }
472 * MessageDialog.prototype.initialize = function () {
473 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
474 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
475 * 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>' );
476 * this.$body.append( this.content.$element );
478 * MessageDialog.prototype.getBodyHeight = function () {
481 * MessageDialog.prototype.getActionProcess = function ( action ) {
483 * if ( action === 'save' ) {
484 * dialog.getActions().get({actions: 'save'})[0].pushPending();
485 * return new OO.ui.Process()
487 * .next( function () {
488 * dialog.getActions().get({actions: 'save'})[0].popPending();
491 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
494 * var windowManager = new OO.ui.WindowManager();
495 * $( 'body' ).append( windowManager.$element );
497 * var dialog = new MessageDialog();
498 * windowManager.addWindows( [ dialog ] );
499 * windowManager.openWindow( dialog );
505 * @param {Object} [config] Configuration options
506 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
508 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
509 // Configuration initialization
510 config
= config
|| {};
514 this.$pending
= null;
517 this.setPendingElement( config
.$pending
|| this.$element
);
522 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
527 * Set the pending element (and clean up any existing one).
529 * @param {jQuery} $pending The element to set to pending.
531 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
532 if ( this.$pending
) {
533 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
536 this.$pending
= $pending
;
537 if ( this.pending
> 0 ) {
538 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
543 * Check if an element is pending.
545 * @return {boolean} Element is pending
547 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
548 return !!this.pending
;
552 * Increase the pending counter. The pending state will remain active until the counter is zero
553 * (i.e., the number of calls to #pushPending and #popPending is the same).
557 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
558 if ( this.pending
=== 0 ) {
559 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
560 this.updateThemeClasses();
568 * Decrease the pending counter. The pending state will remain active until the counter is zero
569 * (i.e., the number of calls to #pushPending and #popPending is the same).
573 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
574 if ( this.pending
=== 1 ) {
575 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
576 this.updateThemeClasses();
578 this.pending
= Math
.max( 0, this.pending
- 1 );
584 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
585 * Actions can be made available for specific contexts (modes) and circumstances
586 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
588 * ActionSets contain two types of actions:
590 * - 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.
591 * - Other: Other actions include all non-special visible actions.
593 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
596 * // Example: An action set used in a process dialog
597 * function MyProcessDialog( config ) {
598 * MyProcessDialog.parent.call( this, config );
600 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
601 * MyProcessDialog.static.title = 'An action set in a process dialog';
602 * // An action set that uses modes ('edit' and 'help' mode, in this example).
603 * MyProcessDialog.static.actions = [
604 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
605 * { action: 'help', modes: 'edit', label: 'Help' },
606 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
607 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
610 * MyProcessDialog.prototype.initialize = function () {
611 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
612 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
613 * 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>' );
614 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
615 * 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>' );
616 * this.stackLayout = new OO.ui.StackLayout( {
617 * items: [ this.panel1, this.panel2 ]
619 * this.$body.append( this.stackLayout.$element );
621 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
622 * return MyProcessDialog.parent.prototype.getSetupProcess.call( this, data )
623 * .next( function () {
624 * this.actions.setMode( 'edit' );
627 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
628 * if ( action === 'help' ) {
629 * this.actions.setMode( 'help' );
630 * this.stackLayout.setItem( this.panel2 );
631 * } else if ( action === 'back' ) {
632 * this.actions.setMode( 'edit' );
633 * this.stackLayout.setItem( this.panel1 );
634 * } else if ( action === 'continue' ) {
636 * return new OO.ui.Process( function () {
640 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
642 * MyProcessDialog.prototype.getBodyHeight = function () {
643 * return this.panel1.$element.outerHeight( true );
645 * var windowManager = new OO.ui.WindowManager();
646 * $( 'body' ).append( windowManager.$element );
647 * var dialog = new MyProcessDialog( {
650 * windowManager.addWindows( [ dialog ] );
651 * windowManager.openWindow( dialog );
653 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
657 * @mixins OO.EventEmitter
660 * @param {Object} [config] Configuration options
662 OO
.ui
.ActionSet
= function OoUiActionSet( config
) {
663 // Configuration initialization
664 config
= config
|| {};
666 // Mixin constructors
667 OO
.EventEmitter
.call( this );
672 actions
: 'getAction',
676 this.categorized
= {};
679 this.organized
= false;
680 this.changing
= false;
681 this.changed
= false;
686 OO
.mixinClass( OO
.ui
.ActionSet
, OO
.EventEmitter
);
688 /* Static Properties */
691 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
692 * header of a {@link OO.ui.ProcessDialog process dialog}.
693 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
695 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
702 OO
.ui
.ActionSet
.static.specialFlags
= [ 'safe', 'primary' ];
709 * A 'click' event is emitted when an action is clicked.
711 * @param {OO.ui.ActionWidget} action Action that was clicked
717 * A 'resize' event is emitted when an action widget is resized.
719 * @param {OO.ui.ActionWidget} action Action that was resized
725 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
727 * @param {OO.ui.ActionWidget[]} added Actions added
733 * A 'remove' event is emitted when actions are {@link #method-remove removed}
734 * or {@link #clear cleared}.
736 * @param {OO.ui.ActionWidget[]} added Actions removed
742 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
743 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
750 * Handle action change events.
755 OO
.ui
.ActionSet
.prototype.onActionChange = function () {
756 this.organized
= false;
757 if ( this.changing
) {
760 this.emit( 'change' );
765 * Check if an action is one of the special actions.
767 * @param {OO.ui.ActionWidget} action Action to check
768 * @return {boolean} Action is special
770 OO
.ui
.ActionSet
.prototype.isSpecial = function ( action
) {
773 for ( flag
in this.special
) {
774 if ( action
=== this.special
[ flag
] ) {
783 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
786 * @param {Object} [filters] Filters to use, omit to get all actions
787 * @param {string|string[]} [filters.actions] Actions that action widgets must have
788 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
789 * @param {string|string[]} [filters.modes] Modes that action widgets must have
790 * @param {boolean} [filters.visible] Action widgets must be visible
791 * @param {boolean} [filters.disabled] Action widgets must be disabled
792 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
794 OO
.ui
.ActionSet
.prototype.get = function ( filters
) {
795 var i
, len
, list
, category
, actions
, index
, match
, matches
;
800 // Collect category candidates
802 for ( category
in this.categorized
) {
803 list
= filters
[ category
];
805 if ( !Array
.isArray( list
) ) {
808 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
809 actions
= this.categorized
[ category
][ list
[ i
] ];
810 if ( Array
.isArray( actions
) ) {
811 matches
.push
.apply( matches
, actions
);
816 // Remove by boolean filters
817 for ( i
= 0, len
= matches
.length
; i
< len
; i
++ ) {
818 match
= matches
[ i
];
820 ( filters
.visible
!== undefined && match
.isVisible() !== filters
.visible
) ||
821 ( filters
.disabled
!== undefined && match
.isDisabled() !== filters
.disabled
)
823 matches
.splice( i
, 1 );
829 for ( i
= 0, len
= matches
.length
; i
< len
; i
++ ) {
830 match
= matches
[ i
];
831 index
= matches
.lastIndexOf( match
);
832 while ( index
!== i
) {
833 matches
.splice( index
, 1 );
835 index
= matches
.lastIndexOf( match
);
840 return this.list
.slice();
844 * Get 'special' actions.
846 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
847 * Special flags can be configured in subclasses by changing the static #specialFlags property.
849 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
851 OO
.ui
.ActionSet
.prototype.getSpecial = function () {
853 return $.extend( {}, this.special
);
857 * Get 'other' actions.
859 * Other actions include all non-special visible action widgets.
861 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
863 OO
.ui
.ActionSet
.prototype.getOthers = function () {
865 return this.others
.slice();
869 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
870 * to be available in the specified mode will be made visible. All other actions will be hidden.
872 * @param {string} mode The mode. Only actions configured to be available in the specified
873 * mode will be made visible.
878 OO
.ui
.ActionSet
.prototype.setMode = function ( mode
) {
881 this.changing
= true;
882 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
883 action
= this.list
[ i
];
884 action
.toggle( action
.hasMode( mode
) );
887 this.organized
= false;
888 this.changing
= false;
889 this.emit( 'change' );
895 * Set the abilities of the specified actions.
897 * Action widgets that are configured with the specified actions will be enabled
898 * or disabled based on the boolean values specified in the `actions`
901 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
902 * values that indicate whether or not the action should be enabled.
905 OO
.ui
.ActionSet
.prototype.setAbilities = function ( actions
) {
906 var i
, len
, action
, item
;
908 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
909 item
= this.list
[ i
];
910 action
= item
.getAction();
911 if ( actions
[ action
] !== undefined ) {
912 item
.setDisabled( !actions
[ action
] );
920 * Executes a function once per action.
922 * When making changes to multiple actions, use this method instead of iterating over the actions
923 * manually to defer emitting a #change event until after all actions have been changed.
925 * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get
926 * @param {Function} callback Callback to run for each action; callback is invoked with three
927 * arguments: the action, the action's index, the list of actions being iterated over
930 OO
.ui
.ActionSet
.prototype.forEach = function ( filter
, callback
) {
931 this.changed
= false;
932 this.changing
= true;
933 this.get( filter
).forEach( callback
);
934 this.changing
= false;
935 if ( this.changed
) {
936 this.emit( 'change' );
943 * Add action widgets to the action set.
945 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
950 OO
.ui
.ActionSet
.prototype.add = function ( actions
) {
953 this.changing
= true;
954 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
955 action
= actions
[ i
];
956 action
.connect( this, {
957 click
: [ 'emit', 'click', action
],
958 resize
: [ 'emit', 'resize', action
],
959 toggle
: [ 'onActionChange' ]
961 this.list
.push( action
);
963 this.organized
= false;
964 this.emit( 'add', actions
);
965 this.changing
= false;
966 this.emit( 'change' );
972 * Remove action widgets from the set.
974 * To remove all actions, you may wish to use the #clear method instead.
976 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
981 OO
.ui
.ActionSet
.prototype.remove = function ( actions
) {
982 var i
, len
, index
, action
;
984 this.changing
= true;
985 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
986 action
= actions
[ i
];
987 index
= this.list
.indexOf( action
);
988 if ( index
!== -1 ) {
989 action
.disconnect( this );
990 this.list
.splice( index
, 1 );
993 this.organized
= false;
994 this.emit( 'remove', actions
);
995 this.changing
= false;
996 this.emit( 'change' );
1002 * Remove all action widets from the set.
1004 * To remove only specified actions, use the {@link #method-remove remove} method instead.
1010 OO
.ui
.ActionSet
.prototype.clear = function () {
1012 removed
= this.list
.slice();
1014 this.changing
= true;
1015 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
1016 action
= this.list
[ i
];
1017 action
.disconnect( this );
1022 this.organized
= false;
1023 this.emit( 'remove', removed
);
1024 this.changing
= false;
1025 this.emit( 'change' );
1033 * This is called whenever organized information is requested. It will only reorganize the actions
1034 * if something has changed since the last time it ran.
1039 OO
.ui
.ActionSet
.prototype.organize = function () {
1040 var i
, iLen
, j
, jLen
, flag
, action
, category
, list
, item
, special
,
1041 specialFlags
= this.constructor.static.specialFlags
;
1043 if ( !this.organized
) {
1044 this.categorized
= {};
1047 for ( i
= 0, iLen
= this.list
.length
; i
< iLen
; i
++ ) {
1048 action
= this.list
[ i
];
1049 if ( action
.isVisible() ) {
1050 // Populate categories
1051 for ( category
in this.categories
) {
1052 if ( !this.categorized
[ category
] ) {
1053 this.categorized
[ category
] = {};
1055 list
= action
[ this.categories
[ category
] ]();
1056 if ( !Array
.isArray( list
) ) {
1059 for ( j
= 0, jLen
= list
.length
; j
< jLen
; j
++ ) {
1061 if ( !this.categorized
[ category
][ item
] ) {
1062 this.categorized
[ category
][ item
] = [];
1064 this.categorized
[ category
][ item
].push( action
);
1067 // Populate special/others
1069 for ( j
= 0, jLen
= specialFlags
.length
; j
< jLen
; j
++ ) {
1070 flag
= specialFlags
[ j
];
1071 if ( !this.special
[ flag
] && action
.hasFlag( flag
) ) {
1072 this.special
[ flag
] = action
;
1078 this.others
.push( action
);
1082 this.organized
= true;
1089 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
1090 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
1091 * connected to them and can't be interacted with.
1097 * @param {Object} [config] Configuration options
1098 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
1099 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
1101 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
1102 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
1103 * @cfg {string} [text] Text to insert
1104 * @cfg {Array} [content] An array of content elements to append (after #text).
1105 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
1106 * Instances of OO.ui.Element will have their $element appended.
1107 * @cfg {jQuery} [$content] Content elements to append (after #text).
1108 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
1109 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
1110 * Data can also be specified with the #setData method.
1112 OO
.ui
.Element
= function OoUiElement( config
) {
1113 // Configuration initialization
1114 config
= config
|| {};
1118 this.visible
= true;
1119 this.data
= config
.data
;
1120 this.$element
= config
.$element
||
1121 $( document
.createElement( this.getTagName() ) );
1122 this.elementGroup
= null;
1123 this.debouncedUpdateThemeClassesHandler
= OO
.ui
.debounce( this.debouncedUpdateThemeClasses
);
1126 if ( Array
.isArray( config
.classes
) ) {
1127 this.$element
.addClass( config
.classes
.join( ' ' ) );
1130 this.$element
.attr( 'id', config
.id
);
1132 if ( config
.text
) {
1133 this.$element
.text( config
.text
);
1135 if ( config
.content
) {
1136 // The `content` property treats plain strings as text; use an
1137 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
1138 // appropriate $element appended.
1139 this.$element
.append( config
.content
.map( function ( v
) {
1140 if ( typeof v
=== 'string' ) {
1141 // Escape string so it is properly represented in HTML.
1142 return document
.createTextNode( v
);
1143 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
1145 return v
.toString();
1146 } else if ( v
instanceof OO
.ui
.Element
) {
1152 if ( config
.$content
) {
1153 // The `$content` property treats plain strings as HTML.
1154 this.$element
.append( config
.$content
);
1160 OO
.initClass( OO
.ui
.Element
);
1162 /* Static Properties */
1165 * The name of the HTML tag used by the element.
1167 * The static value may be ignored if the #getTagName method is overridden.
1171 * @property {string}
1173 OO
.ui
.Element
.static.tagName
= 'div';
1175 /* Static Methods */
1178 * Reconstitute a JavaScript object corresponding to a widget created
1179 * by the PHP implementation.
1181 * @param {string|HTMLElement|jQuery} idOrNode
1182 * A DOM id (if a string) or node for the widget to infuse.
1183 * @return {OO.ui.Element}
1184 * The `OO.ui.Element` corresponding to this (infusable) document node.
1185 * For `Tag` objects emitted on the HTML side (used occasionally for content)
1186 * the value returned is a newly-created Element wrapping around the existing
1189 OO
.ui
.Element
.static.infuse = function ( idOrNode
) {
1190 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, false );
1191 // Verify that the type matches up.
1192 // FIXME: uncomment after T89721 is fixed (see T90929)
1194 if ( !( obj instanceof this['class'] ) ) {
1195 throw new Error( 'Infusion type mismatch!' );
1202 * Implementation helper for `infuse`; skips the type check and has an
1203 * extra property so that only the top-level invocation touches the DOM.
1205 * @param {string|HTMLElement|jQuery} idOrNode
1206 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
1207 * when the top-level widget of this infusion is inserted into DOM,
1208 * replacing the original node; or false for top-level invocation.
1209 * @return {OO.ui.Element}
1211 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, domPromise
) {
1212 // look for a cached result of a previous infusion.
1213 var id
, $elem
, data
, cls
, parts
, parent
, obj
, top
, state
;
1214 if ( typeof idOrNode
=== 'string' ) {
1216 $elem
= $( document
.getElementById( id
) );
1218 $elem
= $( idOrNode
);
1219 id
= $elem
.attr( 'id' );
1221 if ( !$elem
.length
) {
1222 throw new Error( 'Widget not found: ' + id
);
1224 data
= $elem
.data( 'ooui-infused' ) || $elem
[ 0 ].oouiInfused
;
1227 if ( data
=== true ) {
1228 throw new Error( 'Circular dependency! ' + id
);
1232 data
= $elem
.attr( 'data-ooui' );
1234 throw new Error( 'No infusion data found: ' + id
);
1237 data
= $.parseJSON( data
);
1241 if ( !( data
&& data
._
) ) {
1242 throw new Error( 'No valid infusion data found: ' + id
);
1244 if ( data
._
=== 'Tag' ) {
1245 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
1246 return new OO
.ui
.Element( { $element
: $elem
} );
1248 parts
= data
._
.split( '.' );
1249 cls
= OO
.getProp
.apply( OO
, [ window
].concat( parts
) );
1250 if ( cls
=== undefined ) {
1251 // The PHP output might be old and not including the "OO.ui" prefix
1252 // TODO: Remove this back-compat after next major release
1253 cls
= OO
.getProp
.apply( OO
, [ OO
.ui
].concat( parts
) );
1254 if ( cls
=== undefined ) {
1255 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
1259 // Verify that we're creating an OO.ui.Element instance
1260 parent
= cls
.parent
;
1262 while ( parent
!== undefined ) {
1263 if ( parent
=== OO
.ui
.Element
) {
1268 parent
= parent
.parent
;
1271 if ( parent
!== OO
.ui
.Element
) {
1272 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
1275 if ( domPromise
=== false ) {
1277 domPromise
= top
.promise();
1279 $elem
.data( 'ooui-infused', true ); // prevent loops
1280 data
.id
= id
; // implicit
1281 data
= OO
.copy( data
, null, function deserialize( value
) {
1282 if ( OO
.isPlainObject( value
) ) {
1284 return OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, domPromise
);
1287 return new OO
.ui
.HtmlSnippet( value
.html
);
1291 // allow widgets to reuse parts of the DOM
1292 data
= cls
.static.reusePreInfuseDOM( $elem
[ 0 ], data
);
1293 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
1294 state
= cls
.static.gatherPreInfuseState( $elem
[ 0 ], data
);
1296 // jscs:disable requireCapitalizedConstructors
1297 obj
= new cls( data
);
1298 // jscs:enable requireCapitalizedConstructors
1299 // now replace old DOM with this new DOM.
1301 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
1302 // so only mutate the DOM if we need to.
1303 if ( $elem
[ 0 ] !== obj
.$element
[ 0 ] ) {
1304 $elem
.replaceWith( obj
.$element
);
1305 // This element is now gone from the DOM, but if anyone is holding a reference to it,
1306 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
1307 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
1308 $elem
[ 0 ].oouiInfused
= obj
;
1312 obj
.$element
.data( 'ooui-infused', obj
);
1313 // set the 'data-ooui' attribute so we can identify infused widgets
1314 obj
.$element
.attr( 'data-ooui', '' );
1315 // restore dynamic state after the new element is inserted into DOM
1316 domPromise
.done( obj
.restorePreInfuseState
.bind( obj
, state
) );
1321 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
1323 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
1324 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
1325 * constructor, which will be given the enhanced config.
1328 * @param {HTMLElement} node
1329 * @param {Object} config
1332 OO
.ui
.Element
.static.reusePreInfuseDOM = function ( node
, config
) {
1337 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of a HTML DOM node
1338 * (and its children) that represent an Element of the same class and the given configuration,
1339 * generated by the PHP implementation.
1341 * This method is called just before `node` is detached from the DOM. The return value of this
1342 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
1343 * is inserted into DOM to replace `node`.
1346 * @param {HTMLElement} node
1347 * @param {Object} config
1350 OO
.ui
.Element
.static.gatherPreInfuseState = function () {
1355 * Get a jQuery function within a specific document.
1358 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1359 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1361 * @return {Function} Bound jQuery function
1363 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
1364 function wrapper( selector
) {
1365 return $( selector
, wrapper
.context
);
1368 wrapper
.context
= this.getDocument( context
);
1371 wrapper
.$iframe
= $iframe
;
1378 * Get the document of an element.
1381 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1382 * @return {HTMLDocument|null} Document object
1384 OO
.ui
.Element
.static.getDocument = function ( obj
) {
1385 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1386 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
1387 // Empty jQuery selections might have a context
1390 obj
.ownerDocument
||
1394 ( obj
.nodeType
=== 9 && obj
) ||
1399 * Get the window of an element or document.
1402 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1403 * @return {Window} Window object
1405 OO
.ui
.Element
.static.getWindow = function ( obj
) {
1406 var doc
= this.getDocument( obj
);
1408 // Standard Document.defaultView is IE9+
1409 return doc
.parentWindow
|| doc
.defaultView
;
1413 * Get the direction of an element or document.
1416 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1417 * @return {string} Text direction, either 'ltr' or 'rtl'
1419 OO
.ui
.Element
.static.getDir = function ( obj
) {
1422 if ( obj
instanceof jQuery
) {
1425 isDoc
= obj
.nodeType
=== 9;
1426 isWin
= obj
.document
!== undefined;
1427 if ( isDoc
|| isWin
) {
1433 return $( obj
).css( 'direction' );
1437 * Get the offset between two frames.
1439 * TODO: Make this function not use recursion.
1442 * @param {Window} from Window of the child frame
1443 * @param {Window} [to=window] Window of the parent frame
1444 * @param {Object} [offset] Offset to start with, used internally
1445 * @return {Object} Offset object, containing left and top properties
1447 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
1448 var i
, len
, frames
, frame
, rect
;
1454 offset
= { top
: 0, left
: 0 };
1456 if ( from.parent
=== from ) {
1460 // Get iframe element
1461 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
1462 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
1463 if ( frames
[ i
].contentWindow
=== from ) {
1464 frame
= frames
[ i
];
1469 // Recursively accumulate offset values
1471 rect
= frame
.getBoundingClientRect();
1472 offset
.left
+= rect
.left
;
1473 offset
.top
+= rect
.top
;
1474 if ( from !== to
) {
1475 this.getFrameOffset( from.parent
, offset
);
1482 * Get the offset between two elements.
1484 * The two elements may be in a different frame, but in that case the frame $element is in must
1485 * be contained in the frame $anchor is in.
1488 * @param {jQuery} $element Element whose position to get
1489 * @param {jQuery} $anchor Element to get $element's position relative to
1490 * @return {Object} Translated position coordinates, containing top and left properties
1492 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
1493 var iframe
, iframePos
,
1494 pos
= $element
.offset(),
1495 anchorPos
= $anchor
.offset(),
1496 elementDocument
= this.getDocument( $element
),
1497 anchorDocument
= this.getDocument( $anchor
);
1499 // If $element isn't in the same document as $anchor, traverse up
1500 while ( elementDocument
!== anchorDocument
) {
1501 iframe
= elementDocument
.defaultView
.frameElement
;
1503 throw new Error( '$element frame is not contained in $anchor frame' );
1505 iframePos
= $( iframe
).offset();
1506 pos
.left
+= iframePos
.left
;
1507 pos
.top
+= iframePos
.top
;
1508 elementDocument
= iframe
.ownerDocument
;
1510 pos
.left
-= anchorPos
.left
;
1511 pos
.top
-= anchorPos
.top
;
1516 * Get element border sizes.
1519 * @param {HTMLElement} el Element to measure
1520 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1522 OO
.ui
.Element
.static.getBorders = function ( el
) {
1523 var doc
= el
.ownerDocument
,
1525 // Standard Document.defaultView is IE9+
1526 win
= doc
.parentWindow
|| doc
.defaultView
,
1527 style
= win
&& win
.getComputedStyle
?
1528 win
.getComputedStyle( el
, null ) :
1530 // Standard getComputedStyle() is IE9+
1533 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
1534 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
1535 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
1536 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
1547 * Get dimensions of an element or window.
1550 * @param {HTMLElement|Window} el Element to measure
1551 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1553 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1555 doc
= el
.ownerDocument
|| el
.document
,
1557 // Standard Document.defaultView is IE9+
1558 win
= doc
.parentWindow
|| doc
.defaultView
;
1560 if ( win
=== el
|| el
=== doc
.documentElement
) {
1563 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1565 top
: $win
.scrollTop(),
1566 left
: $win
.scrollLeft()
1568 scrollbar
: { right
: 0, bottom
: 0 },
1572 bottom
: $win
.innerHeight(),
1573 right
: $win
.innerWidth()
1579 borders
: this.getBorders( el
),
1581 top
: $el
.scrollTop(),
1582 left
: $el
.scrollLeft()
1585 right
: $el
.innerWidth() - el
.clientWidth
,
1586 bottom
: $el
.innerHeight() - el
.clientHeight
1588 rect
: el
.getBoundingClientRect()
1594 * Get scrollable object parent
1596 * documentElement can't be used to get or set the scrollTop
1597 * property on Blink. Changing and testing its value lets us
1598 * use 'body' or 'documentElement' based on what is working.
1600 * https://code.google.com/p/chromium/issues/detail?id=303131
1603 * @param {HTMLElement} el Element to find scrollable parent for
1604 * @return {HTMLElement} Scrollable parent
1606 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1607 var scrollTop
, body
;
1609 if ( OO
.ui
.scrollableElement
=== undefined ) {
1610 body
= el
.ownerDocument
.body
;
1611 scrollTop
= body
.scrollTop
;
1614 if ( body
.scrollTop
=== 1 ) {
1615 body
.scrollTop
= scrollTop
;
1616 OO
.ui
.scrollableElement
= 'body';
1618 OO
.ui
.scrollableElement
= 'documentElement';
1622 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1626 * Get closest scrollable container.
1628 * Traverses up until either a scrollable element or the root is reached, in which case the window
1632 * @param {HTMLElement} el Element to find scrollable container for
1633 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1634 * @return {HTMLElement} Closest scrollable container
1636 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1638 // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
1639 props
= [ 'overflow-x', 'overflow-y' ],
1640 $parent
= $( el
).parent();
1642 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1643 props
= [ 'overflow-' + dimension
];
1646 while ( $parent
.length
) {
1647 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1648 return $parent
[ 0 ];
1652 val
= $parent
.css( props
[ i
] );
1653 if ( val
=== 'auto' || val
=== 'scroll' ) {
1654 return $parent
[ 0 ];
1657 $parent
= $parent
.parent();
1659 return this.getDocument( el
).body
;
1663 * Scroll element into view.
1666 * @param {HTMLElement} el Element to scroll into view
1667 * @param {Object} [config] Configuration options
1668 * @param {string} [config.duration] jQuery animation duration value
1669 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1670 * to scroll in both directions
1671 * @param {Function} [config.complete] Function to call when scrolling completes
1673 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1674 var rel
, anim
, callback
, sc
, $sc
, eld
, scd
, $win
;
1676 // Configuration initialization
1677 config
= config
|| {};
1680 callback
= typeof config
.complete
=== 'function' && config
.complete
;
1681 sc
= this.getClosestScrollableContainer( el
, config
.direction
);
1683 eld
= this.getDimensions( el
);
1684 scd
= this.getDimensions( sc
);
1685 $win
= $( this.getWindow( el
) );
1687 // Compute the distances between the edges of el and the edges of the scroll viewport
1688 if ( $sc
.is( 'html, body' ) ) {
1689 // If the scrollable container is the root, this is easy
1692 bottom
: $win
.innerHeight() - eld
.rect
.bottom
,
1693 left
: eld
.rect
.left
,
1694 right
: $win
.innerWidth() - eld
.rect
.right
1697 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1699 top
: eld
.rect
.top
- ( scd
.rect
.top
+ scd
.borders
.top
),
1700 bottom
: scd
.rect
.bottom
- scd
.borders
.bottom
- scd
.scrollbar
.bottom
- eld
.rect
.bottom
,
1701 left
: eld
.rect
.left
- ( scd
.rect
.left
+ scd
.borders
.left
),
1702 right
: scd
.rect
.right
- scd
.borders
.right
- scd
.scrollbar
.right
- eld
.rect
.right
1706 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1707 if ( rel
.top
< 0 ) {
1708 anim
.scrollTop
= scd
.scroll
.top
+ rel
.top
;
1709 } else if ( rel
.top
> 0 && rel
.bottom
< 0 ) {
1710 anim
.scrollTop
= scd
.scroll
.top
+ Math
.min( rel
.top
, -rel
.bottom
);
1713 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1714 if ( rel
.left
< 0 ) {
1715 anim
.scrollLeft
= scd
.scroll
.left
+ rel
.left
;
1716 } else if ( rel
.left
> 0 && rel
.right
< 0 ) {
1717 anim
.scrollLeft
= scd
.scroll
.left
+ Math
.min( rel
.left
, -rel
.right
);
1720 if ( !$.isEmptyObject( anim
) ) {
1721 $sc
.stop( true ).animate( anim
, config
.duration
|| 'fast' );
1723 $sc
.queue( function ( next
) {
1736 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1737 * and reserve space for them, because it probably doesn't.
1739 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1740 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1741 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1742 * and then reattach (or show) them back.
1745 * @param {HTMLElement} el Element to reconsider the scrollbars on
1747 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1748 var i
, len
, scrollLeft
, scrollTop
, nodes
= [];
1749 // Save scroll position
1750 scrollLeft
= el
.scrollLeft
;
1751 scrollTop
= el
.scrollTop
;
1752 // Detach all children
1753 while ( el
.firstChild
) {
1754 nodes
.push( el
.firstChild
);
1755 el
.removeChild( el
.firstChild
);
1758 void el
.offsetHeight
;
1759 // Reattach all children
1760 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1761 el
.appendChild( nodes
[ i
] );
1763 // Restore scroll position (no-op if scrollbars disappeared)
1764 el
.scrollLeft
= scrollLeft
;
1765 el
.scrollTop
= scrollTop
;
1771 * Toggle visibility of an element.
1773 * @param {boolean} [show] Make element visible, omit to toggle visibility
1777 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1778 show
= show
=== undefined ? !this.visible
: !!show
;
1780 if ( show
!== this.isVisible() ) {
1781 this.visible
= show
;
1782 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1783 this.emit( 'toggle', show
);
1790 * Check if element is visible.
1792 * @return {boolean} element is visible
1794 OO
.ui
.Element
.prototype.isVisible = function () {
1795 return this.visible
;
1801 * @return {Mixed} Element data
1803 OO
.ui
.Element
.prototype.getData = function () {
1810 * @param {Mixed} Element data
1813 OO
.ui
.Element
.prototype.setData = function ( data
) {
1819 * Check if element supports one or more methods.
1821 * @param {string|string[]} methods Method or list of methods to check
1822 * @return {boolean} All methods are supported
1824 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1828 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1829 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1830 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1835 return methods
.length
=== support
;
1839 * Update the theme-provided classes.
1841 * @localdoc This is called in element mixins and widget classes any time state changes.
1842 * Updating is debounced, minimizing overhead of changing multiple attributes and
1843 * guaranteeing that theme updates do not occur within an element's constructor
1845 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1846 this.debouncedUpdateThemeClassesHandler();
1851 * @localdoc This method is called directly from the QUnit tests instead of #updateThemeClasses, to
1852 * make them synchronous.
1854 OO
.ui
.Element
.prototype.debouncedUpdateThemeClasses = function () {
1855 OO
.ui
.theme
.updateElementClasses( this );
1859 * Get the HTML tag name.
1861 * Override this method to base the result on instance information.
1863 * @return {string} HTML tag name
1865 OO
.ui
.Element
.prototype.getTagName = function () {
1866 return this.constructor.static.tagName
;
1870 * Check if the element is attached to the DOM
1871 * @return {boolean} The element is attached to the DOM
1873 OO
.ui
.Element
.prototype.isElementAttached = function () {
1874 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1878 * Get the DOM document.
1880 * @return {HTMLDocument} Document object
1882 OO
.ui
.Element
.prototype.getElementDocument = function () {
1883 // Don't cache this in other ways either because subclasses could can change this.$element
1884 return OO
.ui
.Element
.static.getDocument( this.$element
);
1888 * Get the DOM window.
1890 * @return {Window} Window object
1892 OO
.ui
.Element
.prototype.getElementWindow = function () {
1893 return OO
.ui
.Element
.static.getWindow( this.$element
);
1897 * Get closest scrollable container.
1899 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1900 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1904 * Get group element is in.
1906 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1908 OO
.ui
.Element
.prototype.getElementGroup = function () {
1909 return this.elementGroup
;
1913 * Set group element is in.
1915 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1918 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1919 this.elementGroup
= group
;
1924 * Scroll element into view.
1926 * @param {Object} [config] Configuration options
1928 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1929 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1933 * Restore the pre-infusion dynamic state for this widget.
1935 * This method is called after #$element has been inserted into DOM. The parameter is the return
1936 * value of #gatherPreInfuseState.
1939 * @param {Object} state
1941 OO
.ui
.Element
.prototype.restorePreInfuseState = function () {
1945 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1946 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1947 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1948 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1949 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1953 * @extends OO.ui.Element
1954 * @mixins OO.EventEmitter
1957 * @param {Object} [config] Configuration options
1959 OO
.ui
.Layout
= function OoUiLayout( config
) {
1960 // Configuration initialization
1961 config
= config
|| {};
1963 // Parent constructor
1964 OO
.ui
.Layout
.parent
.call( this, config
);
1966 // Mixin constructors
1967 OO
.EventEmitter
.call( this );
1970 this.$element
.addClass( 'oo-ui-layout' );
1975 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1976 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1979 * Widgets are compositions of one or more OOjs UI elements that users can both view
1980 * and interact with. All widgets can be configured and modified via a standard API,
1981 * and their state can change dynamically according to a model.
1985 * @extends OO.ui.Element
1986 * @mixins OO.EventEmitter
1989 * @param {Object} [config] Configuration options
1990 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1991 * appearance reflects this state.
1993 OO
.ui
.Widget
= function OoUiWidget( config
) {
1994 // Initialize config
1995 config
= $.extend( { disabled
: false }, config
);
1997 // Parent constructor
1998 OO
.ui
.Widget
.parent
.call( this, config
);
2000 // Mixin constructors
2001 OO
.EventEmitter
.call( this );
2004 this.disabled
= null;
2005 this.wasDisabled
= null;
2008 this.$element
.addClass( 'oo-ui-widget' );
2009 this.setDisabled( !!config
.disabled
);
2014 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
2015 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
2017 /* Static Properties */
2020 * Whether this widget will behave reasonably when wrapped in a HTML `<label>`. If this is true,
2021 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
2026 * @property {boolean}
2028 OO
.ui
.Widget
.static.supportsSimpleLabel
= false;
2035 * A 'disable' event is emitted when the disabled state of the widget changes
2036 * (i.e. on disable **and** enable).
2038 * @param {boolean} disabled Widget is disabled
2044 * A 'toggle' event is emitted when the visibility of the widget changes.
2046 * @param {boolean} visible Widget is visible
2052 * Check if the widget is disabled.
2054 * @return {boolean} Widget is disabled
2056 OO
.ui
.Widget
.prototype.isDisabled = function () {
2057 return this.disabled
;
2061 * Set the 'disabled' state of the widget.
2063 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
2065 * @param {boolean} disabled Disable widget
2068 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
2071 this.disabled
= !!disabled
;
2072 isDisabled
= this.isDisabled();
2073 if ( isDisabled
!== this.wasDisabled
) {
2074 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
2075 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
2076 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
2077 this.emit( 'disable', isDisabled
);
2078 this.updateThemeClasses();
2080 this.wasDisabled
= isDisabled
;
2086 * Update the disabled state, in case of changes in parent widget.
2090 OO
.ui
.Widget
.prototype.updateDisabled = function () {
2091 this.setDisabled( this.disabled
);
2096 * A window is a container for elements that are in a child frame. They are used with
2097 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
2098 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
2099 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
2100 * the window manager will choose a sensible fallback.
2102 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
2103 * different processes are executed:
2105 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
2106 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
2109 * - {@link #getSetupProcess} method is called and its result executed
2110 * - {@link #getReadyProcess} method is called and its result executed
2112 * **opened**: The window is now open
2114 * **closing**: The closing stage begins when the window manager's
2115 * {@link OO.ui.WindowManager#closeWindow closeWindow}
2116 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
2118 * - {@link #getHoldProcess} method is called and its result executed
2119 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
2121 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
2122 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
2123 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
2124 * processing can complete. Always assume window processes are executed asynchronously.
2126 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2128 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
2132 * @extends OO.ui.Element
2133 * @mixins OO.EventEmitter
2136 * @param {Object} [config] Configuration options
2137 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
2138 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
2140 OO
.ui
.Window
= function OoUiWindow( config
) {
2141 // Configuration initialization
2142 config
= config
|| {};
2144 // Parent constructor
2145 OO
.ui
.Window
.parent
.call( this, config
);
2147 // Mixin constructors
2148 OO
.EventEmitter
.call( this );
2151 this.manager
= null;
2152 this.size
= config
.size
|| this.constructor.static.size
;
2153 this.$frame
= $( '<div>' );
2154 this.$overlay
= $( '<div>' );
2155 this.$content
= $( '<div>' );
2157 this.$focusTrapBefore
= $( '<div>' ).prop( 'tabIndex', 0 );
2158 this.$focusTrapAfter
= $( '<div>' ).prop( 'tabIndex', 0 );
2159 this.$focusTraps
= this.$focusTrapBefore
.add( this.$focusTrapAfter
);
2162 this.$overlay
.addClass( 'oo-ui-window-overlay' );
2164 .addClass( 'oo-ui-window-content' )
2165 .attr( 'tabindex', 0 );
2167 .addClass( 'oo-ui-window-frame' )
2168 .append( this.$focusTrapBefore
, this.$content
, this.$focusTrapAfter
);
2171 .addClass( 'oo-ui-window' )
2172 .append( this.$frame
, this.$overlay
);
2174 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
2175 // that reference properties not initialized at that time of parent class construction
2176 // TODO: Find a better way to handle post-constructor setup
2177 this.visible
= false;
2178 this.$element
.addClass( 'oo-ui-element-hidden' );
2183 OO
.inheritClass( OO
.ui
.Window
, OO
.ui
.Element
);
2184 OO
.mixinClass( OO
.ui
.Window
, OO
.EventEmitter
);
2186 /* Static Properties */
2189 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
2191 * The static size is used if no #size is configured during construction.
2195 * @property {string}
2197 OO
.ui
.Window
.static.size
= 'medium';
2202 * Handle mouse down events.
2205 * @param {jQuery.Event} e Mouse down event
2207 OO
.ui
.Window
.prototype.onMouseDown = function ( e
) {
2208 // Prevent clicking on the click-block from stealing focus
2209 if ( e
.target
=== this.$element
[ 0 ] ) {
2215 * Check if the window has been initialized.
2217 * Initialization occurs when a window is added to a manager.
2219 * @return {boolean} Window has been initialized
2221 OO
.ui
.Window
.prototype.isInitialized = function () {
2222 return !!this.manager
;
2226 * Check if the window is visible.
2228 * @return {boolean} Window is visible
2230 OO
.ui
.Window
.prototype.isVisible = function () {
2231 return this.visible
;
2235 * Check if the window is opening.
2237 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
2240 * @return {boolean} Window is opening
2242 OO
.ui
.Window
.prototype.isOpening = function () {
2243 return this.manager
.isOpening( this );
2247 * Check if the window is closing.
2249 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
2251 * @return {boolean} Window is closing
2253 OO
.ui
.Window
.prototype.isClosing = function () {
2254 return this.manager
.isClosing( this );
2258 * Check if the window is opened.
2260 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
2262 * @return {boolean} Window is opened
2264 OO
.ui
.Window
.prototype.isOpened = function () {
2265 return this.manager
.isOpened( this );
2269 * Get the window manager.
2271 * All windows must be attached to a window manager, which is used to open
2272 * and close the window and control its presentation.
2274 * @return {OO.ui.WindowManager} Manager of window
2276 OO
.ui
.Window
.prototype.getManager = function () {
2277 return this.manager
;
2281 * Get the symbolic name of the window size (e.g., `small` or `medium`).
2283 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
2285 OO
.ui
.Window
.prototype.getSize = function () {
2286 var viewport
= OO
.ui
.Element
.static.getDimensions( this.getElementWindow() ),
2287 sizes
= this.manager
.constructor.static.sizes
,
2290 if ( !sizes
[ size
] ) {
2291 size
= this.manager
.constructor.static.defaultSize
;
2293 if ( size
!== 'full' && viewport
.rect
.right
- viewport
.rect
.left
< sizes
[ size
].width
) {
2301 * Get the size properties associated with the current window size
2303 * @return {Object} Size properties
2305 OO
.ui
.Window
.prototype.getSizeProperties = function () {
2306 return this.manager
.constructor.static.sizes
[ this.getSize() ];
2310 * Disable transitions on window's frame for the duration of the callback function, then enable them
2314 * @param {Function} callback Function to call while transitions are disabled
2316 OO
.ui
.Window
.prototype.withoutSizeTransitions = function ( callback
) {
2317 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2318 // Disable transitions first, otherwise we'll get values from when the window was animating.
2320 styleObj
= this.$frame
[ 0 ].style
;
2321 oldTransition
= styleObj
.transition
|| styleObj
.OTransition
|| styleObj
.MsTransition
||
2322 styleObj
.MozTransition
|| styleObj
.WebkitTransition
;
2323 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
2324 styleObj
.MozTransition
= styleObj
.WebkitTransition
= 'none';
2326 // Force reflow to make sure the style changes done inside callback really are not transitioned
2327 this.$frame
.height();
2328 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
2329 styleObj
.MozTransition
= styleObj
.WebkitTransition
= oldTransition
;
2333 * Get the height of the full window contents (i.e., the window head, body and foot together).
2335 * What consistitutes the head, body, and foot varies depending on the window type.
2336 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
2337 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
2338 * and special actions in the head, and dialog content in the body.
2340 * To get just the height of the dialog body, use the #getBodyHeight method.
2342 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
2344 OO
.ui
.Window
.prototype.getContentHeight = function () {
2347 bodyStyleObj
= this.$body
[ 0 ].style
,
2348 frameStyleObj
= this.$frame
[ 0 ].style
;
2350 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2351 // Disable transitions first, otherwise we'll get values from when the window was animating.
2352 this.withoutSizeTransitions( function () {
2353 var oldHeight
= frameStyleObj
.height
,
2354 oldPosition
= bodyStyleObj
.position
;
2355 frameStyleObj
.height
= '1px';
2356 // Force body to resize to new width
2357 bodyStyleObj
.position
= 'relative';
2358 bodyHeight
= win
.getBodyHeight();
2359 frameStyleObj
.height
= oldHeight
;
2360 bodyStyleObj
.position
= oldPosition
;
2364 // Add buffer for border
2365 ( this.$frame
.outerHeight() - this.$frame
.innerHeight() ) +
2366 // Use combined heights of children
2367 ( this.$head
.outerHeight( true ) + bodyHeight
+ this.$foot
.outerHeight( true ) )
2372 * Get the height of the window body.
2374 * To get the height of the full window contents (the window body, head, and foot together),
2375 * use #getContentHeight.
2377 * When this function is called, the window will temporarily have been resized
2378 * to height=1px, so .scrollHeight measurements can be taken accurately.
2380 * @return {number} Height of the window body in pixels
2382 OO
.ui
.Window
.prototype.getBodyHeight = function () {
2383 return this.$body
[ 0 ].scrollHeight
;
2387 * Get the directionality of the frame (right-to-left or left-to-right).
2389 * @return {string} Directionality: `'ltr'` or `'rtl'`
2391 OO
.ui
.Window
.prototype.getDir = function () {
2392 return OO
.ui
.Element
.static.getDir( this.$content
) || 'ltr';
2396 * Get the 'setup' process.
2398 * The setup process is used to set up a window for use in a particular context,
2399 * based on the `data` argument. This method is called during the opening phase of the window’s
2402 * Override this method to add additional steps to the ‘setup’ process the parent method provides
2403 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2406 * To add window content that persists between openings, you may wish to use the #initialize method
2409 * @param {Object} [data] Window opening data
2410 * @return {OO.ui.Process} Setup process
2412 OO
.ui
.Window
.prototype.getSetupProcess = function () {
2413 return new OO
.ui
.Process();
2417 * Get the ‘ready’ process.
2419 * The ready process is used to ready a window for use in a particular
2420 * context, based on the `data` argument. This method is called during the opening phase of
2421 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2423 * Override this method to add additional steps to the ‘ready’ process the parent method
2424 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2425 * methods of OO.ui.Process.
2427 * @param {Object} [data] Window opening data
2428 * @return {OO.ui.Process} Ready process
2430 OO
.ui
.Window
.prototype.getReadyProcess = function () {
2431 return new OO
.ui
.Process();
2435 * Get the 'hold' process.
2437 * The hold proccess is used to keep a window from being used in a particular context,
2438 * based on the `data` argument. This method is called during the closing phase of the window’s
2441 * Override this method to add additional steps to the 'hold' process the parent method provides
2442 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2445 * @param {Object} [data] Window closing data
2446 * @return {OO.ui.Process} Hold process
2448 OO
.ui
.Window
.prototype.getHoldProcess = function () {
2449 return new OO
.ui
.Process();
2453 * Get the ‘teardown’ process.
2455 * The teardown process is used to teardown a window after use. During teardown,
2456 * user interactions within the window are conveyed and the window is closed, based on the `data`
2457 * argument. This method is called during the closing phase of the window’s lifecycle.
2459 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2460 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2463 * @param {Object} [data] Window closing data
2464 * @return {OO.ui.Process} Teardown process
2466 OO
.ui
.Window
.prototype.getTeardownProcess = function () {
2467 return new OO
.ui
.Process();
2471 * Set the window manager.
2473 * This will cause the window to initialize. Calling it more than once will cause an error.
2475 * @param {OO.ui.WindowManager} manager Manager for this window
2476 * @throws {Error} An error is thrown if the method is called more than once
2479 OO
.ui
.Window
.prototype.setManager = function ( manager
) {
2480 if ( this.manager
) {
2481 throw new Error( 'Cannot set window manager, window already has a manager' );
2484 this.manager
= manager
;
2491 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2493 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2497 OO
.ui
.Window
.prototype.setSize = function ( size
) {
2504 * Update the window size.
2506 * @throws {Error} An error is thrown if the window is not attached to a window manager
2509 OO
.ui
.Window
.prototype.updateSize = function () {
2510 if ( !this.manager
) {
2511 throw new Error( 'Cannot update window size, must be attached to a manager' );
2514 this.manager
.updateWindowSize( this );
2520 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2521 * when the window is opening. In general, setDimensions should not be called directly.
2523 * To set the size of the window, use the #setSize method.
2525 * @param {Object} dim CSS dimension properties
2526 * @param {string|number} [dim.width] Width
2527 * @param {string|number} [dim.minWidth] Minimum width
2528 * @param {string|number} [dim.maxWidth] Maximum width
2529 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2530 * @param {string|number} [dim.minWidth] Minimum height
2531 * @param {string|number} [dim.maxWidth] Maximum height
2534 OO
.ui
.Window
.prototype.setDimensions = function ( dim
) {
2537 styleObj
= this.$frame
[ 0 ].style
;
2539 // Calculate the height we need to set using the correct width
2540 if ( dim
.height
=== undefined ) {
2541 this.withoutSizeTransitions( function () {
2542 var oldWidth
= styleObj
.width
;
2543 win
.$frame
.css( 'width', dim
.width
|| '' );
2544 height
= win
.getContentHeight();
2545 styleObj
.width
= oldWidth
;
2548 height
= dim
.height
;
2552 width
: dim
.width
|| '',
2553 minWidth
: dim
.minWidth
|| '',
2554 maxWidth
: dim
.maxWidth
|| '',
2555 height
: height
|| '',
2556 minHeight
: dim
.minHeight
|| '',
2557 maxHeight
: dim
.maxHeight
|| ''
2564 * Initialize window contents.
2566 * Before the window is opened for the first time, #initialize is called so that content that
2567 * persists between openings can be added to the window.
2569 * To set up a window with new content each time the window opens, use #getSetupProcess.
2571 * @throws {Error} An error is thrown if the window is not attached to a window manager
2574 OO
.ui
.Window
.prototype.initialize = function () {
2575 if ( !this.manager
) {
2576 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2580 this.$head
= $( '<div>' );
2581 this.$body
= $( '<div>' );
2582 this.$foot
= $( '<div>' );
2583 this.$document
= $( this.getElementDocument() );
2586 this.$element
.on( 'mousedown', this.onMouseDown
.bind( this ) );
2589 this.$head
.addClass( 'oo-ui-window-head' );
2590 this.$body
.addClass( 'oo-ui-window-body' );
2591 this.$foot
.addClass( 'oo-ui-window-foot' );
2592 this.$content
.append( this.$head
, this.$body
, this.$foot
);
2598 * Called when someone tries to focus the hidden element at the end of the dialog.
2599 * Sends focus back to the start of the dialog.
2601 * @param {jQuery.Event} event Focus event
2603 OO
.ui
.Window
.prototype.onFocusTrapFocused = function ( event
) {
2604 if ( this.$focusTrapBefore
.is( event
.target
) ) {
2605 OO
.ui
.findFocusable( this.$content
, true ).focus();
2607 // this.$content is the part of the focus cycle, and is the first focusable element
2608 this.$content
.focus();
2615 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2616 * method, which returns a promise resolved when the window is done opening.
2618 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2620 * @param {Object} [data] Window opening data
2621 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2622 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2623 * value is a new promise, which is resolved when the window begins closing.
2624 * @throws {Error} An error is thrown if the window is not attached to a window manager
2626 OO
.ui
.Window
.prototype.open = function ( data
) {
2627 if ( !this.manager
) {
2628 throw new Error( 'Cannot open window, must be attached to a manager' );
2631 return this.manager
.openWindow( this, data
);
2637 * This method is a wrapper around a call to the window
2638 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2639 * which returns a closing promise resolved when the window is done closing.
2641 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2642 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2643 * the window closes.
2645 * @param {Object} [data] Window closing data
2646 * @return {jQuery.Promise} Promise resolved when window is closed
2647 * @throws {Error} An error is thrown if the window is not attached to a window manager
2649 OO
.ui
.Window
.prototype.close = function ( data
) {
2650 if ( !this.manager
) {
2651 throw new Error( 'Cannot close window, must be attached to a manager' );
2654 return this.manager
.closeWindow( this, data
);
2660 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2663 * @param {Object} [data] Window opening data
2664 * @return {jQuery.Promise} Promise resolved when window is setup
2666 OO
.ui
.Window
.prototype.setup = function ( data
) {
2669 this.toggle( true );
2671 this.focusTrapHandler
= OO
.ui
.bind( this.onFocusTrapFocused
, this );
2672 this.$focusTraps
.on( 'focus', this.focusTrapHandler
);
2674 return this.getSetupProcess( data
).execute().then( function () {
2675 // Force redraw by asking the browser to measure the elements' widths
2676 win
.$element
.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2677 win
.$content
.addClass( 'oo-ui-window-content-setup' ).width();
2684 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2687 * @param {Object} [data] Window opening data
2688 * @return {jQuery.Promise} Promise resolved when window is ready
2690 OO
.ui
.Window
.prototype.ready = function ( data
) {
2693 this.$content
.focus();
2694 return this.getReadyProcess( data
).execute().then( function () {
2695 // Force redraw by asking the browser to measure the elements' widths
2696 win
.$element
.addClass( 'oo-ui-window-ready' ).width();
2697 win
.$content
.addClass( 'oo-ui-window-content-ready' ).width();
2704 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2707 * @param {Object} [data] Window closing data
2708 * @return {jQuery.Promise} Promise resolved when window is held
2710 OO
.ui
.Window
.prototype.hold = function ( data
) {
2713 return this.getHoldProcess( data
).execute().then( function () {
2714 // Get the focused element within the window's content
2715 var $focus
= win
.$content
.find( OO
.ui
.Element
.static.getDocument( win
.$content
).activeElement
);
2717 // Blur the focused element
2718 if ( $focus
.length
) {
2722 // Force redraw by asking the browser to measure the elements' widths
2723 win
.$element
.removeClass( 'oo-ui-window-ready' ).width();
2724 win
.$content
.removeClass( 'oo-ui-window-content-ready' ).width();
2731 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2734 * @param {Object} [data] Window closing data
2735 * @return {jQuery.Promise} Promise resolved when window is torn down
2737 OO
.ui
.Window
.prototype.teardown = function ( data
) {
2740 return this.getTeardownProcess( data
).execute().then( function () {
2741 // Force redraw by asking the browser to measure the elements' widths
2742 win
.$element
.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2743 win
.$content
.removeClass( 'oo-ui-window-content-setup' ).width();
2744 win
.$focusTraps
.off( 'focus', win
.focusTrapHandler
);
2745 win
.toggle( false );
2750 * The Dialog class serves as the base class for the other types of dialogs.
2751 * Unless extended to include controls, the rendered dialog box is a simple window
2752 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2753 * which opens, closes, and controls the presentation of the window. See the
2754 * [OOjs UI documentation on MediaWiki] [1] for more information.
2757 * // A simple dialog window.
2758 * function MyDialog( config ) {
2759 * MyDialog.parent.call( this, config );
2761 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2762 * MyDialog.prototype.initialize = function () {
2763 * MyDialog.parent.prototype.initialize.call( this );
2764 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2765 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2766 * this.$body.append( this.content.$element );
2768 * MyDialog.prototype.getBodyHeight = function () {
2769 * return this.content.$element.outerHeight( true );
2771 * var myDialog = new MyDialog( {
2774 * // Create and append a window manager, which opens and closes the window.
2775 * var windowManager = new OO.ui.WindowManager();
2776 * $( 'body' ).append( windowManager.$element );
2777 * windowManager.addWindows( [ myDialog ] );
2778 * // Open the window!
2779 * windowManager.openWindow( myDialog );
2781 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2785 * @extends OO.ui.Window
2786 * @mixins OO.ui.mixin.PendingElement
2789 * @param {Object} [config] Configuration options
2791 OO
.ui
.Dialog
= function OoUiDialog( config
) {
2792 // Parent constructor
2793 OO
.ui
.Dialog
.parent
.call( this, config
);
2795 // Mixin constructors
2796 OO
.ui
.mixin
.PendingElement
.call( this );
2799 this.actions
= new OO
.ui
.ActionSet();
2800 this.attachedActions
= [];
2801 this.currentAction
= null;
2802 this.onDialogKeyDownHandler
= this.onDialogKeyDown
.bind( this );
2805 this.actions
.connect( this, {
2806 click
: 'onActionClick',
2807 resize
: 'onActionResize',
2808 change
: 'onActionsChange'
2813 .addClass( 'oo-ui-dialog' )
2814 .attr( 'role', 'dialog' );
2819 OO
.inheritClass( OO
.ui
.Dialog
, OO
.ui
.Window
);
2820 OO
.mixinClass( OO
.ui
.Dialog
, OO
.ui
.mixin
.PendingElement
);
2822 /* Static Properties */
2825 * Symbolic name of dialog.
2827 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2828 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2830 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2835 * @property {string}
2837 OO
.ui
.Dialog
.static.name
= '';
2842 * The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function
2843 * that will produce a Label node or string. The title can also be specified with data passed to the
2844 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2849 * @property {jQuery|string|Function}
2851 OO
.ui
.Dialog
.static.title
= '';
2854 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2856 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2857 * value will be overriden.
2859 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2863 * @property {Object[]}
2865 OO
.ui
.Dialog
.static.actions
= [];
2868 * Close the dialog when the 'Esc' key is pressed.
2873 * @property {boolean}
2875 OO
.ui
.Dialog
.static.escapable
= true;
2880 * Handle frame document key down events.
2883 * @param {jQuery.Event} e Key down event
2885 OO
.ui
.Dialog
.prototype.onDialogKeyDown = function ( e
) {
2886 if ( e
.which
=== OO
.ui
.Keys
.ESCAPE
) {
2889 e
.stopPropagation();
2894 * Handle action resized events.
2897 * @param {OO.ui.ActionWidget} action Action that was resized
2899 OO
.ui
.Dialog
.prototype.onActionResize = function () {
2900 // Override in subclass
2904 * Handle action click events.
2907 * @param {OO.ui.ActionWidget} action Action that was clicked
2909 OO
.ui
.Dialog
.prototype.onActionClick = function ( action
) {
2910 if ( !this.isPending() ) {
2911 this.executeAction( action
.getAction() );
2916 * Handle actions change event.
2920 OO
.ui
.Dialog
.prototype.onActionsChange = function () {
2921 this.detachActions();
2922 if ( !this.isClosing() ) {
2923 this.attachActions();
2928 * Get the set of actions used by the dialog.
2930 * @return {OO.ui.ActionSet}
2932 OO
.ui
.Dialog
.prototype.getActions = function () {
2933 return this.actions
;
2937 * Get a process for taking action.
2939 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2940 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2941 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2943 * @param {string} [action] Symbolic name of action
2944 * @return {OO.ui.Process} Action process
2946 OO
.ui
.Dialog
.prototype.getActionProcess = function ( action
) {
2947 return new OO
.ui
.Process()
2948 .next( function () {
2950 // An empty action always closes the dialog without data, which should always be
2951 // safe and make no changes
2960 * @param {Object} [data] Dialog opening data
2961 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2962 * the {@link #static-title static title}
2963 * @param {Object[]} [data.actions] List of configuration options for each
2964 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2966 OO
.ui
.Dialog
.prototype.getSetupProcess = function ( data
) {
2970 return OO
.ui
.Dialog
.parent
.prototype.getSetupProcess
.call( this, data
)
2971 .next( function () {
2972 var config
= this.constructor.static,
2973 actions
= data
.actions
!== undefined ? data
.actions
: config
.actions
;
2975 this.title
.setLabel(
2976 data
.title
!== undefined ? data
.title
: this.constructor.static.title
2978 this.actions
.add( this.getActionWidgets( actions
) );
2980 if ( this.constructor.static.escapable
) {
2981 this.$element
.on( 'keydown', this.onDialogKeyDownHandler
);
2989 OO
.ui
.Dialog
.prototype.getTeardownProcess = function ( data
) {
2991 return OO
.ui
.Dialog
.parent
.prototype.getTeardownProcess
.call( this, data
)
2992 .first( function () {
2993 if ( this.constructor.static.escapable
) {
2994 this.$element
.off( 'keydown', this.onDialogKeyDownHandler
);
2997 this.actions
.clear();
2998 this.currentAction
= null;
3005 OO
.ui
.Dialog
.prototype.initialize = function () {
3009 OO
.ui
.Dialog
.parent
.prototype.initialize
.call( this );
3011 titleId
= OO
.ui
.generateElementId();
3014 this.title
= new OO
.ui
.LabelWidget( {
3019 this.$content
.addClass( 'oo-ui-dialog-content' );
3020 this.$element
.attr( 'aria-labelledby', titleId
);
3021 this.setPendingElement( this.$head
);
3025 * Get action widgets from a list of configs
3027 * @param {Object[]} actions Action widget configs
3028 * @return {OO.ui.ActionWidget[]} Action widgets
3030 OO
.ui
.Dialog
.prototype.getActionWidgets = function ( actions
) {
3031 var i
, len
, widgets
= [];
3032 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
3034 new OO
.ui
.ActionWidget( actions
[ i
] )
3041 * Attach action actions.
3045 OO
.ui
.Dialog
.prototype.attachActions = function () {
3046 // Remember the list of potentially attached actions
3047 this.attachedActions
= this.actions
.get();
3051 * Detach action actions.
3056 OO
.ui
.Dialog
.prototype.detachActions = function () {
3059 // Detach all actions that may have been previously attached
3060 for ( i
= 0, len
= this.attachedActions
.length
; i
< len
; i
++ ) {
3061 this.attachedActions
[ i
].$element
.detach();
3063 this.attachedActions
= [];
3067 * Execute an action.
3069 * @param {string} action Symbolic name of action to execute
3070 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
3072 OO
.ui
.Dialog
.prototype.executeAction = function ( action
) {
3074 this.currentAction
= action
;
3075 return this.getActionProcess( action
).execute()
3076 .always( this.popPending
.bind( this ) );
3080 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
3081 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
3082 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
3083 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
3084 * pertinent data and reused.
3086 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
3087 * `opened`, and `closing`, which represent the primary stages of the cycle:
3089 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
3090 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
3092 * - an `opening` event is emitted with an `opening` promise
3093 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
3094 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
3095 * window and its result executed
3096 * - a `setup` progress notification is emitted from the `opening` promise
3097 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
3098 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
3099 * window and its result executed
3100 * - a `ready` progress notification is emitted from the `opening` promise
3101 * - the `opening` promise is resolved with an `opened` promise
3103 * **Opened**: the window is now open.
3105 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
3106 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
3107 * to close the window.
3109 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
3110 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
3111 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
3112 * window and its result executed
3113 * - a `hold` progress notification is emitted from the `closing` promise
3114 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
3115 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
3116 * window and its result executed
3117 * - a `teardown` progress notification is emitted from the `closing` promise
3118 * - the `closing` promise is resolved. The window is now closed
3120 * See the [OOjs UI documentation on MediaWiki][1] for more information.
3122 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3125 * @extends OO.ui.Element
3126 * @mixins OO.EventEmitter
3129 * @param {Object} [config] Configuration options
3130 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
3131 * Note that window classes that are instantiated with a factory must have
3132 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
3133 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
3135 OO
.ui
.WindowManager
= function OoUiWindowManager( config
) {
3136 // Configuration initialization
3137 config
= config
|| {};
3139 // Parent constructor
3140 OO
.ui
.WindowManager
.parent
.call( this, config
);
3142 // Mixin constructors
3143 OO
.EventEmitter
.call( this );
3146 this.factory
= config
.factory
;
3147 this.modal
= config
.modal
=== undefined || !!config
.modal
;
3149 this.opening
= null;
3151 this.closing
= null;
3152 this.preparingToOpen
= null;
3153 this.preparingToClose
= null;
3154 this.currentWindow
= null;
3155 this.globalEvents
= false;
3156 this.$ariaHidden
= null;
3157 this.onWindowResizeTimeout
= null;
3158 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
3159 this.afterWindowResizeHandler
= this.afterWindowResize
.bind( this );
3163 .addClass( 'oo-ui-windowManager' )
3164 .toggleClass( 'oo-ui-windowManager-modal', this.modal
);
3169 OO
.inheritClass( OO
.ui
.WindowManager
, OO
.ui
.Element
);
3170 OO
.mixinClass( OO
.ui
.WindowManager
, OO
.EventEmitter
);
3175 * An 'opening' event is emitted when the window begins to be opened.
3178 * @param {OO.ui.Window} win Window that's being opened
3179 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
3180 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
3181 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
3182 * @param {Object} data Window opening data
3186 * A 'closing' event is emitted when the window begins to be closed.
3189 * @param {OO.ui.Window} win Window that's being closed
3190 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
3191 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
3192 * processes are complete. When the `closing` promise is resolved, the first argument of its value
3193 * is the closing data.
3194 * @param {Object} data Window closing data
3198 * A 'resize' event is emitted when a window is resized.
3201 * @param {OO.ui.Window} win Window that was resized
3204 /* Static Properties */
3207 * Map of the symbolic name of each window size and its CSS properties.
3211 * @property {Object}
3213 OO
.ui
.WindowManager
.static.sizes
= {
3227 // These can be non-numeric because they are never used in calculations
3234 * Symbolic name of the default window size.
3236 * The default size is used if the window's requested size is not recognized.
3240 * @property {string}
3242 OO
.ui
.WindowManager
.static.defaultSize
= 'medium';
3247 * Handle window resize events.
3250 * @param {jQuery.Event} e Window resize event
3252 OO
.ui
.WindowManager
.prototype.onWindowResize = function () {
3253 clearTimeout( this.onWindowResizeTimeout
);
3254 this.onWindowResizeTimeout
= setTimeout( this.afterWindowResizeHandler
, 200 );
3258 * Handle window resize events.
3261 * @param {jQuery.Event} e Window resize event
3263 OO
.ui
.WindowManager
.prototype.afterWindowResize = function () {
3264 if ( this.currentWindow
) {
3265 this.updateWindowSize( this.currentWindow
);
3270 * Check if window is opening.
3272 * @return {boolean} Window is opening
3274 OO
.ui
.WindowManager
.prototype.isOpening = function ( win
) {
3275 return win
=== this.currentWindow
&& !!this.opening
&& this.opening
.state() === 'pending';
3279 * Check if window is closing.
3281 * @return {boolean} Window is closing
3283 OO
.ui
.WindowManager
.prototype.isClosing = function ( win
) {
3284 return win
=== this.currentWindow
&& !!this.closing
&& this.closing
.state() === 'pending';
3288 * Check if window is opened.
3290 * @return {boolean} Window is opened
3292 OO
.ui
.WindowManager
.prototype.isOpened = function ( win
) {
3293 return win
=== this.currentWindow
&& !!this.opened
&& this.opened
.state() === 'pending';
3297 * Check if a window is being managed.
3299 * @param {OO.ui.Window} win Window to check
3300 * @return {boolean} Window is being managed
3302 OO
.ui
.WindowManager
.prototype.hasWindow = function ( win
) {
3305 for ( name
in this.windows
) {
3306 if ( this.windows
[ name
] === win
) {
3315 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
3317 * @param {OO.ui.Window} win Window being opened
3318 * @param {Object} [data] Window opening data
3319 * @return {number} Milliseconds to wait
3321 OO
.ui
.WindowManager
.prototype.getSetupDelay = function () {
3326 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
3328 * @param {OO.ui.Window} win Window being opened
3329 * @param {Object} [data] Window opening data
3330 * @return {number} Milliseconds to wait
3332 OO
.ui
.WindowManager
.prototype.getReadyDelay = function () {
3337 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
3339 * @param {OO.ui.Window} win Window being closed
3340 * @param {Object} [data] Window closing data
3341 * @return {number} Milliseconds to wait
3343 OO
.ui
.WindowManager
.prototype.getHoldDelay = function () {
3348 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
3349 * executing the ‘teardown’ process.
3351 * @param {OO.ui.Window} win Window being closed
3352 * @param {Object} [data] Window closing data
3353 * @return {number} Milliseconds to wait
3355 OO
.ui
.WindowManager
.prototype.getTeardownDelay = function () {
3356 return this.modal
? 250 : 0;
3360 * Get a window by its symbolic name.
3362 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
3363 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
3364 * for more information about using factories.
3365 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3367 * @param {string} name Symbolic name of the window
3368 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
3369 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
3370 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
3372 OO
.ui
.WindowManager
.prototype.getWindow = function ( name
) {
3373 var deferred
= $.Deferred(),
3374 win
= this.windows
[ name
];
3376 if ( !( win
instanceof OO
.ui
.Window
) ) {
3377 if ( this.factory
) {
3378 if ( !this.factory
.lookup( name
) ) {
3379 deferred
.reject( new OO
.ui
.Error(
3380 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
3383 win
= this.factory
.create( name
);
3384 this.addWindows( [ win
] );
3385 deferred
.resolve( win
);
3388 deferred
.reject( new OO
.ui
.Error(
3389 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
3393 deferred
.resolve( win
);
3396 return deferred
.promise();
3400 * Get current window.
3402 * @return {OO.ui.Window|null} Currently opening/opened/closing window
3404 OO
.ui
.WindowManager
.prototype.getCurrentWindow = function () {
3405 return this.currentWindow
;
3411 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
3412 * @param {Object} [data] Window opening data
3413 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3414 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3417 OO
.ui
.WindowManager
.prototype.openWindow = function ( win
, data
) {
3419 opening
= $.Deferred();
3421 // Argument handling
3422 if ( typeof win
=== 'string' ) {
3423 return this.getWindow( win
).then( function ( win
) {
3424 return manager
.openWindow( win
, data
);
3429 if ( !this.hasWindow( win
) ) {
3430 opening
.reject( new OO
.ui
.Error(
3431 'Cannot open window: window is not attached to manager'
3433 } else if ( this.preparingToOpen
|| this.opening
|| this.opened
) {
3434 opening
.reject( new OO
.ui
.Error(
3435 'Cannot open window: another window is opening or open'
3440 if ( opening
.state() !== 'rejected' ) {
3441 // If a window is currently closing, wait for it to complete
3442 this.preparingToOpen
= $.when( this.closing
);
3443 // Ensure handlers get called after preparingToOpen is set
3444 this.preparingToOpen
.done( function () {
3445 if ( manager
.modal
) {
3446 manager
.toggleGlobalEvents( true );
3447 manager
.toggleAriaIsolation( true );
3449 manager
.currentWindow
= win
;
3450 manager
.opening
= opening
;
3451 manager
.preparingToOpen
= null;
3452 manager
.emit( 'opening', win
, opening
, data
);
3453 setTimeout( function () {
3454 win
.setup( data
).then( function () {
3455 manager
.updateWindowSize( win
);
3456 manager
.opening
.notify( { state
: 'setup' } );
3457 setTimeout( function () {
3458 win
.ready( data
).then( function () {
3459 manager
.opening
.notify( { state
: 'ready' } );
3460 manager
.opening
= null;
3461 manager
.opened
= $.Deferred();
3462 opening
.resolve( manager
.opened
.promise(), data
);
3464 manager
.opening
= null;
3465 manager
.opened
= $.Deferred();
3467 manager
.closeWindow( win
);
3469 }, manager
.getReadyDelay() );
3471 manager
.opening
= null;
3472 manager
.opened
= $.Deferred();
3474 manager
.closeWindow( win
);
3476 }, manager
.getSetupDelay() );
3480 return opening
.promise();
3486 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3487 * @param {Object} [data] Window closing data
3488 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3489 * See {@link #event-closing 'closing' event} for more information about closing promises.
3490 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3493 OO
.ui
.WindowManager
.prototype.closeWindow = function ( win
, data
) {
3495 closing
= $.Deferred(),
3498 // Argument handling
3499 if ( typeof win
=== 'string' ) {
3500 win
= this.windows
[ win
];
3501 } else if ( !this.hasWindow( win
) ) {
3507 closing
.reject( new OO
.ui
.Error(
3508 'Cannot close window: window is not attached to manager'
3510 } else if ( win
!== this.currentWindow
) {
3511 closing
.reject( new OO
.ui
.Error(
3512 'Cannot close window: window already closed with different data'
3514 } else if ( this.preparingToClose
|| this.closing
) {
3515 closing
.reject( new OO
.ui
.Error(
3516 'Cannot close window: window already closing with different data'
3521 if ( closing
.state() !== 'rejected' ) {
3522 // If the window is currently opening, close it when it's done
3523 this.preparingToClose
= $.when( this.opening
);
3524 // Ensure handlers get called after preparingToClose is set
3525 this.preparingToClose
.always( function () {
3526 manager
.closing
= closing
;
3527 manager
.preparingToClose
= null;
3528 manager
.emit( 'closing', win
, closing
, data
);
3529 opened
= manager
.opened
;
3530 manager
.opened
= null;
3531 opened
.resolve( closing
.promise(), data
);
3532 setTimeout( function () {
3533 win
.hold( data
).then( function () {
3534 closing
.notify( { state
: 'hold' } );
3535 setTimeout( function () {
3536 win
.teardown( data
).then( function () {
3537 closing
.notify( { state
: 'teardown' } );
3538 if ( manager
.modal
) {
3539 manager
.toggleGlobalEvents( false );
3540 manager
.toggleAriaIsolation( false );
3542 manager
.closing
= null;
3543 manager
.currentWindow
= null;
3544 closing
.resolve( data
);
3546 }, manager
.getTeardownDelay() );
3548 }, manager
.getHoldDelay() );
3552 return closing
.promise();
3556 * Add windows to the window manager.
3558 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3559 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3560 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3562 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3563 * by reference, symbolic name, or explicitly defined symbolic names.
3564 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3565 * explicit nor a statically configured symbolic name.
3567 OO
.ui
.WindowManager
.prototype.addWindows = function ( windows
) {
3568 var i
, len
, win
, name
, list
;
3570 if ( Array
.isArray( windows
) ) {
3571 // Convert to map of windows by looking up symbolic names from static configuration
3573 for ( i
= 0, len
= windows
.length
; i
< len
; i
++ ) {
3574 name
= windows
[ i
].constructor.static.name
;
3575 if ( typeof name
!== 'string' ) {
3576 throw new Error( 'Cannot add window' );
3578 list
[ name
] = windows
[ i
];
3580 } else if ( OO
.isPlainObject( windows
) ) {
3585 for ( name
in list
) {
3587 this.windows
[ name
] = win
.toggle( false );
3588 this.$element
.append( win
.$element
);
3589 win
.setManager( this );
3594 * Remove the specified windows from the windows manager.
3596 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3597 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3598 * longer listens to events, use the #destroy method.
3600 * @param {string[]} names Symbolic names of windows to remove
3601 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3602 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3604 OO
.ui
.WindowManager
.prototype.removeWindows = function ( names
) {
3605 var i
, len
, win
, name
, cleanupWindow
,
3608 cleanup = function ( name
, win
) {
3609 delete manager
.windows
[ name
];
3610 win
.$element
.detach();
3613 for ( i
= 0, len
= names
.length
; i
< len
; i
++ ) {
3615 win
= this.windows
[ name
];
3617 throw new Error( 'Cannot remove window' );
3619 cleanupWindow
= cleanup
.bind( null, name
, win
);
3620 promises
.push( this.closeWindow( name
).then( cleanupWindow
, cleanupWindow
) );
3623 return $.when
.apply( $, promises
);
3627 * Remove all windows from the window manager.
3629 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3630 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3631 * To remove just a subset of windows, use the #removeWindows method.
3633 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3635 OO
.ui
.WindowManager
.prototype.clearWindows = function () {
3636 return this.removeWindows( Object
.keys( this.windows
) );
3640 * Set dialog size. In general, this method should not be called directly.
3642 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3646 OO
.ui
.WindowManager
.prototype.updateWindowSize = function ( win
) {
3649 // Bypass for non-current, and thus invisible, windows
3650 if ( win
!== this.currentWindow
) {
3654 isFullscreen
= win
.getSize() === 'full';
3656 this.$element
.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen
);
3657 this.$element
.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen
);
3658 win
.setDimensions( win
.getSizeProperties() );
3660 this.emit( 'resize', win
);
3666 * Bind or unbind global events for scrolling.
3669 * @param {boolean} [on] Bind global events
3672 OO
.ui
.WindowManager
.prototype.toggleGlobalEvents = function ( on
) {
3673 var scrollWidth
, bodyMargin
,
3674 $body
= $( this.getElementDocument().body
),
3675 // We could have multiple window managers open so only modify
3676 // the body css at the bottom of the stack
3677 stackDepth
= $body
.data( 'windowManagerGlobalEvents' ) || 0 ;
3679 on
= on
=== undefined ? !!this.globalEvents
: !!on
;
3682 if ( !this.globalEvents
) {
3683 $( this.getElementWindow() ).on( {
3684 // Start listening for top-level window dimension changes
3685 'orientationchange resize': this.onWindowResizeHandler
3687 if ( stackDepth
=== 0 ) {
3688 scrollWidth
= window
.innerWidth
- document
.documentElement
.clientWidth
;
3689 bodyMargin
= parseFloat( $body
.css( 'margin-right' ) ) || 0;
3692 'margin-right': bodyMargin
+ scrollWidth
3696 this.globalEvents
= true;
3698 } else if ( this.globalEvents
) {
3699 $( this.getElementWindow() ).off( {
3700 // Stop listening for top-level window dimension changes
3701 'orientationchange resize': this.onWindowResizeHandler
3704 if ( stackDepth
=== 0 ) {
3710 this.globalEvents
= false;
3712 $body
.data( 'windowManagerGlobalEvents', stackDepth
);
3718 * Toggle screen reader visibility of content other than the window manager.
3721 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3724 OO
.ui
.WindowManager
.prototype.toggleAriaIsolation = function ( isolate
) {
3725 isolate
= isolate
=== undefined ? !this.$ariaHidden
: !!isolate
;
3728 if ( !this.$ariaHidden
) {
3729 // Hide everything other than the window manager from screen readers
3730 this.$ariaHidden
= $( 'body' )
3732 .not( this.$element
.parentsUntil( 'body' ).last() )
3733 .attr( 'aria-hidden', '' );
3735 } else if ( this.$ariaHidden
) {
3736 // Restore screen reader visibility
3737 this.$ariaHidden
.removeAttr( 'aria-hidden' );
3738 this.$ariaHidden
= null;
3745 * Destroy the window manager.
3747 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3748 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3751 OO
.ui
.WindowManager
.prototype.destroy = function () {
3752 this.toggleGlobalEvents( false );
3753 this.toggleAriaIsolation( false );
3754 this.clearWindows();
3755 this.$element
.remove();
3759 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3760 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3761 * appearance and functionality of the error interface.
3763 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3764 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3765 * that initiated the failed process will be disabled.
3767 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3770 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3772 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3777 * @param {string|jQuery} message Description of error
3778 * @param {Object} [config] Configuration options
3779 * @cfg {boolean} [recoverable=true] Error is recoverable.
3780 * By default, errors are recoverable, and users can try the process again.
3781 * @cfg {boolean} [warning=false] Error is a warning.
3782 * If the error is a warning, the error interface will include a
3783 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3784 * is not triggered a second time if the user chooses to continue.
3786 OO
.ui
.Error
= function OoUiError( message
, config
) {
3787 // Allow passing positional parameters inside the config object
3788 if ( OO
.isPlainObject( message
) && config
=== undefined ) {
3790 message
= config
.message
;
3793 // Configuration initialization
3794 config
= config
|| {};
3797 this.message
= message
instanceof jQuery
? message
: String( message
);
3798 this.recoverable
= config
.recoverable
=== undefined || !!config
.recoverable
;
3799 this.warning
= !!config
.warning
;
3804 OO
.initClass( OO
.ui
.Error
);
3809 * Check if the error is recoverable.
3811 * If the error is recoverable, users are able to try the process again.
3813 * @return {boolean} Error is recoverable
3815 OO
.ui
.Error
.prototype.isRecoverable = function () {
3816 return this.recoverable
;
3820 * Check if the error is a warning.
3822 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3824 * @return {boolean} Error is warning
3826 OO
.ui
.Error
.prototype.isWarning = function () {
3827 return this.warning
;
3831 * Get error message as DOM nodes.
3833 * @return {jQuery} Error message in DOM nodes
3835 OO
.ui
.Error
.prototype.getMessage = function () {
3836 return this.message
instanceof jQuery
?
3837 this.message
.clone() :
3838 $( '<div>' ).text( this.message
).contents();
3842 * Get the error message text.
3844 * @return {string} Error message
3846 OO
.ui
.Error
.prototype.getMessageText = function () {
3847 return this.message
instanceof jQuery
? this.message
.text() : this.message
;
3851 * Wraps an HTML snippet for use with configuration values which default
3852 * to strings. This bypasses the default html-escaping done to string
3858 * @param {string} [content] HTML content
3860 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
3862 this.content
= content
;
3867 OO
.initClass( OO
.ui
.HtmlSnippet
);
3874 * @return {string} Unchanged HTML snippet.
3876 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
3877 return this.content
;
3881 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3884 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3885 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3886 * or stop if the promise is rejected.
3887 * - **function**: the process will execute the function. The process will stop if the function returns
3888 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3889 * will wait for that number of milliseconds before proceeding.
3891 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3892 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3893 * its remaining steps will not be performed.
3898 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3899 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3900 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3901 * a number or promise.
3902 * @return {Object} Step object, with `callback` and `context` properties
3904 OO
.ui
.Process = function ( step
, context
) {
3909 if ( step
!== undefined ) {
3910 this.next( step
, context
);
3916 OO
.initClass( OO
.ui
.Process
);
3921 * Start the process.
3923 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
3924 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
3925 * and any remaining steps are not performed.
3927 OO
.ui
.Process
.prototype.execute = function () {
3928 var i
, len
, promise
;
3931 * Continue execution.
3934 * @param {Array} step A function and the context it should be called in
3935 * @return {Function} Function that continues the process
3937 function proceed( step
) {
3938 return function () {
3939 // Execute step in the correct context
3941 result
= step
.callback
.call( step
.context
);
3943 if ( result
=== false ) {
3944 // Use rejected promise for boolean false results
3945 return $.Deferred().reject( [] ).promise();
3947 if ( typeof result
=== 'number' ) {
3949 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3951 // Use a delayed promise for numbers, expecting them to be in milliseconds
3952 deferred
= $.Deferred();
3953 setTimeout( deferred
.resolve
, result
);
3954 return deferred
.promise();
3956 if ( result
instanceof OO
.ui
.Error
) {
3957 // Use rejected promise for error
3958 return $.Deferred().reject( [ result
] ).promise();
3960 if ( Array
.isArray( result
) && result
.length
&& result
[ 0 ] instanceof OO
.ui
.Error
) {
3961 // Use rejected promise for list of errors
3962 return $.Deferred().reject( result
).promise();
3964 // Duck-type the object to see if it can produce a promise
3965 if ( result
&& $.isFunction( result
.promise
) ) {
3966 // Use a promise generated from the result
3967 return result
.promise();
3969 // Use resolved promise for other results
3970 return $.Deferred().resolve().promise();
3974 if ( this.steps
.length
) {
3975 // Generate a chain reaction of promises
3976 promise
= proceed( this.steps
[ 0 ] )();
3977 for ( i
= 1, len
= this.steps
.length
; i
< len
; i
++ ) {
3978 promise
= promise
.then( proceed( this.steps
[ i
] ) );
3981 promise
= $.Deferred().resolve().promise();
3988 * Create a process step.
3991 * @param {number|jQuery.Promise|Function} step
3993 * - Number of milliseconds to wait before proceeding
3994 * - Promise that must be resolved before proceeding
3995 * - Function to execute
3996 * - If the function returns a boolean false the process will stop
3997 * - If the function returns a promise, the process will continue to the next
3998 * step when the promise is resolved or stop if the promise is rejected
3999 * - If the function returns a number, the process will wait for that number of
4000 * milliseconds before proceeding
4001 * @param {Object} [context=null] Execution context of the function. The context is
4002 * ignored if the step is a number or promise.
4003 * @return {Object} Step object, with `callback` and `context` properties
4005 OO
.ui
.Process
.prototype.createStep = function ( step
, context
) {
4006 if ( typeof step
=== 'number' || $.isFunction( step
.promise
) ) {
4008 callback: function () {
4014 if ( $.isFunction( step
) ) {
4020 throw new Error( 'Cannot create process step: number, promise or function expected' );
4024 * Add step to the beginning of the process.
4026 * @inheritdoc #createStep
4027 * @return {OO.ui.Process} this
4030 OO
.ui
.Process
.prototype.first = function ( step
, context
) {
4031 this.steps
.unshift( this.createStep( step
, context
) );
4036 * Add step to the end of the process.
4038 * @inheritdoc #createStep
4039 * @return {OO.ui.Process} this
4042 OO
.ui
.Process
.prototype.next = function ( step
, context
) {
4043 this.steps
.push( this.createStep( step
, context
) );
4048 * A ToolFactory creates tools on demand. All tools ({@link OO.ui.Tool Tools}, {@link OO.ui.PopupTool PopupTools},
4049 * and {@link OO.ui.ToolGroupTool ToolGroupTools}) must be registered with a tool factory. Tools are
4050 * registered by their symbolic name. See {@link OO.ui.Toolbar toolbars} for an example.
4052 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4054 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4057 * @extends OO.Factory
4060 OO
.ui
.ToolFactory
= function OoUiToolFactory() {
4061 // Parent constructor
4062 OO
.ui
.ToolFactory
.parent
.call( this );
4067 OO
.inheritClass( OO
.ui
.ToolFactory
, OO
.Factory
);
4072 * Get tools from the factory
4074 * @param {Array} include Included tools
4075 * @param {Array} exclude Excluded tools
4076 * @param {Array} promote Promoted tools
4077 * @param {Array} demote Demoted tools
4078 * @return {string[]} List of tools
4080 OO
.ui
.ToolFactory
.prototype.getTools = function ( include
, exclude
, promote
, demote
) {
4081 var i
, len
, included
, promoted
, demoted
,
4085 // Collect included and not excluded tools
4086 included
= OO
.simpleArrayDifference( this.extract( include
), this.extract( exclude
) );
4089 promoted
= this.extract( promote
, used
);
4090 demoted
= this.extract( demote
, used
);
4093 for ( i
= 0, len
= included
.length
; i
< len
; i
++ ) {
4094 if ( !used
[ included
[ i
] ] ) {
4095 auto
.push( included
[ i
] );
4099 return promoted
.concat( auto
).concat( demoted
);
4103 * Get a flat list of names from a list of names or groups.
4105 * Tools can be specified in the following ways:
4107 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
4108 * - All tools in a group: `{ group: 'group-name' }`
4109 * - All tools: `'*'`
4112 * @param {Array|string} collection List of tools
4113 * @param {Object} [used] Object with names that should be skipped as properties; extracted
4114 * names will be added as properties
4115 * @return {string[]} List of extracted names
4117 OO
.ui
.ToolFactory
.prototype.extract = function ( collection
, used
) {
4118 var i
, len
, item
, name
, tool
,
4121 if ( collection
=== '*' ) {
4122 for ( name
in this.registry
) {
4123 tool
= this.registry
[ name
];
4125 // Only add tools by group name when auto-add is enabled
4126 tool
.static.autoAddToCatchall
&&
4127 // Exclude already used tools
4128 ( !used
|| !used
[ name
] )
4132 used
[ name
] = true;
4136 } else if ( Array
.isArray( collection
) ) {
4137 for ( i
= 0, len
= collection
.length
; i
< len
; i
++ ) {
4138 item
= collection
[ i
];
4139 // Allow plain strings as shorthand for named tools
4140 if ( typeof item
=== 'string' ) {
4141 item
= { name
: item
};
4143 if ( OO
.isPlainObject( item
) ) {
4145 for ( name
in this.registry
) {
4146 tool
= this.registry
[ name
];
4148 // Include tools with matching group
4149 tool
.static.group
=== item
.group
&&
4150 // Only add tools by group name when auto-add is enabled
4151 tool
.static.autoAddToGroup
&&
4152 // Exclude already used tools
4153 ( !used
|| !used
[ name
] )
4157 used
[ name
] = true;
4161 // Include tools with matching name and exclude already used tools
4162 } else if ( item
.name
&& ( !used
|| !used
[ item
.name
] ) ) {
4163 names
.push( item
.name
);
4165 used
[ item
.name
] = true;
4175 * ToolGroupFactories create {@link OO.ui.ToolGroup toolgroups} on demand. The toolgroup classes must
4176 * specify a symbolic name and be registered with the factory. The following classes are registered by
4179 * - {@link OO.ui.BarToolGroup BarToolGroups} (‘bar’)
4180 * - {@link OO.ui.MenuToolGroup MenuToolGroups} (‘menu’)
4181 * - {@link OO.ui.ListToolGroup ListToolGroups} (‘list’)
4183 * See {@link OO.ui.Toolbar toolbars} for an example.
4185 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4187 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4189 * @extends OO.Factory
4192 OO
.ui
.ToolGroupFactory
= function OoUiToolGroupFactory() {
4193 var i
, l
, defaultClasses
;
4194 // Parent constructor
4195 OO
.Factory
.call( this );
4197 defaultClasses
= this.constructor.static.getDefaultClasses();
4199 // Register default toolgroups
4200 for ( i
= 0, l
= defaultClasses
.length
; i
< l
; i
++ ) {
4201 this.register( defaultClasses
[ i
] );
4207 OO
.inheritClass( OO
.ui
.ToolGroupFactory
, OO
.Factory
);
4209 /* Static Methods */
4212 * Get a default set of classes to be registered on construction.
4214 * @return {Function[]} Default classes
4216 OO
.ui
.ToolGroupFactory
.static.getDefaultClasses = function () {
4219 OO
.ui
.ListToolGroup
,
4231 * @param {Object} [config] Configuration options
4233 OO
.ui
.Theme
= function OoUiTheme( config
) {
4234 // Configuration initialization
4235 config
= config
|| {};
4240 OO
.initClass( OO
.ui
.Theme
);
4245 * Get a list of classes to be applied to a widget.
4247 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
4248 * otherwise state transitions will not work properly.
4250 * @param {OO.ui.Element} element Element for which to get classes
4251 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4253 OO
.ui
.Theme
.prototype.getElementClasses = function () {
4254 return { on
: [], off
: [] };
4258 * Update CSS classes provided by the theme.
4260 * For elements with theme logic hooks, this should be called any time there's a state change.
4262 * @param {OO.ui.Element} element Element for which to update classes
4263 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4265 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
4266 var $elements
= $( [] ),
4267 classes
= this.getElementClasses( element
);
4269 if ( element
.$icon
) {
4270 $elements
= $elements
.add( element
.$icon
);
4272 if ( element
.$indicator
) {
4273 $elements
= $elements
.add( element
.$indicator
);
4277 .removeClass( classes
.off
.join( ' ' ) )
4278 .addClass( classes
.on
.join( ' ' ) );
4282 * RequestManager is a mixin that manages the lifecycle of a promise-backed request for a widget, such as
4283 * the {@link OO.ui.mixin.LookupElement}.
4290 OO
.ui
.mixin
.RequestManager
= function OoUiMixinRequestManager() {
4291 this.requestCache
= {};
4292 this.requestQuery
= null;
4293 this.requestRequest
= null;
4298 OO
.initClass( OO
.ui
.mixin
.RequestManager
);
4301 * Get request results for the current query.
4303 * @return {jQuery.Promise} Promise object which will be passed response data as the first argument of
4304 * the done event. If the request was aborted to make way for a subsequent request, this promise
4305 * may not be rejected, depending on what jQuery feels like doing.
4307 OO
.ui
.mixin
.RequestManager
.prototype.getRequestData = function () {
4309 value
= this.getRequestQuery(),
4310 deferred
= $.Deferred(),
4313 this.abortRequest();
4314 if ( Object
.prototype.hasOwnProperty
.call( this.requestCache
, value
) ) {
4315 deferred
.resolve( this.requestCache
[ value
] );
4317 if ( this.pushPending
) {
4320 this.requestQuery
= value
;
4321 ourRequest
= this.requestRequest
= this.getRequest();
4323 .always( function () {
4324 // We need to pop pending even if this is an old request, otherwise
4325 // the widget will remain pending forever.
4326 // TODO: this assumes that an aborted request will fail or succeed soon after
4327 // being aborted, or at least eventually. It would be nice if we could popPending()
4328 // at abort time, but only if we knew that we hadn't already called popPending()
4329 // for that request.
4330 if ( widget
.popPending
) {
4331 widget
.popPending();
4334 .done( function ( response
) {
4335 // If this is an old request (and aborting it somehow caused it to still succeed),
4336 // ignore its success completely
4337 if ( ourRequest
=== widget
.requestRequest
) {
4338 widget
.requestQuery
= null;
4339 widget
.requestRequest
= null;
4340 widget
.requestCache
[ value
] = widget
.getRequestCacheDataFromResponse( response
);
4341 deferred
.resolve( widget
.requestCache
[ value
] );
4344 .fail( function () {
4345 // If this is an old request (or a request failing because it's being aborted),
4346 // ignore its failure completely
4347 if ( ourRequest
=== widget
.requestRequest
) {
4348 widget
.requestQuery
= null;
4349 widget
.requestRequest
= null;
4354 return deferred
.promise();
4358 * Abort the currently pending request, if any.
4362 OO
.ui
.mixin
.RequestManager
.prototype.abortRequest = function () {
4363 var oldRequest
= this.requestRequest
;
4365 // First unset this.requestRequest to the fail handler will notice
4366 // that the request is no longer current
4367 this.requestRequest
= null;
4368 this.requestQuery
= null;
4374 * Get the query to be made.
4379 * @return {string} query to be used
4381 OO
.ui
.mixin
.RequestManager
.prototype.getRequestQuery
= null;
4384 * Get a new request object of the current query value.
4389 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
4391 OO
.ui
.mixin
.RequestManager
.prototype.getRequest
= null;
4394 * Pre-process data returned by the request from #getRequest.
4396 * The return value of this function will be cached, and any further queries for the given value
4397 * will use the cache rather than doing API requests.
4402 * @param {Mixed} response Response from server
4403 * @return {Mixed} Cached result data
4405 OO
.ui
.mixin
.RequestManager
.prototype.getRequestCacheDataFromResponse
= null;
4408 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
4409 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
4410 * order in which users will navigate through the focusable elements via the "tab" key.
4413 * // TabIndexedElement is mixed into the ButtonWidget class
4414 * // to provide a tabIndex property.
4415 * var button1 = new OO.ui.ButtonWidget( {
4419 * var button2 = new OO.ui.ButtonWidget( {
4423 * var button3 = new OO.ui.ButtonWidget( {
4427 * var button4 = new OO.ui.ButtonWidget( {
4431 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
4437 * @param {Object} [config] Configuration options
4438 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
4439 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
4440 * functionality will be applied to it instead.
4441 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
4442 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
4443 * to remove the element from the tab-navigation flow.
4445 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
4446 // Configuration initialization
4447 config
= $.extend( { tabIndex
: 0 }, config
);
4450 this.$tabIndexed
= null;
4451 this.tabIndex
= null;
4454 this.connect( this, { disable
: 'onTabIndexedElementDisable' } );
4457 this.setTabIndex( config
.tabIndex
);
4458 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
4463 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
4468 * Set the element that should use the tabindex functionality.
4470 * This method is used to retarget a tabindex mixin so that its functionality applies
4471 * to the specified element. If an element is currently using the functionality, the mixin’s
4472 * effect on that element is removed before the new element is set up.
4474 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
4477 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
4478 var tabIndex
= this.tabIndex
;
4479 // Remove attributes from old $tabIndexed
4480 this.setTabIndex( null );
4481 // Force update of new $tabIndexed
4482 this.$tabIndexed
= $tabIndexed
;
4483 this.tabIndex
= tabIndex
;
4484 return this.updateTabIndex();
4488 * Set the value of the tabindex.
4490 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
4493 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
4494 tabIndex
= typeof tabIndex
=== 'number' ? tabIndex
: null;
4496 if ( this.tabIndex
!== tabIndex
) {
4497 this.tabIndex
= tabIndex
;
4498 this.updateTabIndex();
4505 * Update the `tabindex` attribute, in case of changes to tab index or
4511 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
4512 if ( this.$tabIndexed
) {
4513 if ( this.tabIndex
!== null ) {
4514 // Do not index over disabled elements
4515 this.$tabIndexed
.attr( {
4516 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
4517 // Support: ChromeVox and NVDA
4518 // These do not seem to inherit aria-disabled from parent elements
4519 'aria-disabled': this.isDisabled().toString()
4522 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
4529 * Handle disable events.
4532 * @param {boolean} disabled Element is disabled
4534 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
4535 this.updateTabIndex();
4539 * Get the value of the tabindex.
4541 * @return {number|null} Tabindex value
4543 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
4544 return this.tabIndex
;
4548 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
4549 * interface element that can be configured with access keys for accessibility.
4550 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
4552 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
4557 * @param {Object} [config] Configuration options
4558 * @cfg {jQuery} [$button] The button element created by the class.
4559 * If this configuration is omitted, the button element will use a generated `<a>`.
4560 * @cfg {boolean} [framed=true] Render the button with a frame
4562 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
4563 // Configuration initialization
4564 config
= config
|| {};
4567 this.$button
= null;
4569 this.active
= false;
4570 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
4571 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
4572 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
4573 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
4574 this.onClickHandler
= this.onClick
.bind( this );
4575 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
4578 this.$element
.addClass( 'oo-ui-buttonElement' );
4579 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
4580 this.setButtonElement( config
.$button
|| $( '<a>' ) );
4585 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
4587 /* Static Properties */
4590 * Cancel mouse down events.
4592 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4593 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4594 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4599 * @property {boolean}
4601 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
4606 * A 'click' event is emitted when the button element is clicked.
4614 * Set the button element.
4616 * This method is used to retarget a button mixin so that its functionality applies to
4617 * the specified button element instead of the one created by the class. If a button element
4618 * is already set, the method will remove the mixin’s effect on that element.
4620 * @param {jQuery} $button Element to use as button
4622 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
4623 if ( this.$button
) {
4625 .removeClass( 'oo-ui-buttonElement-button' )
4626 .removeAttr( 'role accesskey' )
4628 mousedown
: this.onMouseDownHandler
,
4629 keydown
: this.onKeyDownHandler
,
4630 click
: this.onClickHandler
,
4631 keypress
: this.onKeyPressHandler
4635 this.$button
= $button
4636 .addClass( 'oo-ui-buttonElement-button' )
4637 .attr( { role
: 'button' } )
4639 mousedown
: this.onMouseDownHandler
,
4640 keydown
: this.onKeyDownHandler
,
4641 click
: this.onClickHandler
,
4642 keypress
: this.onKeyPressHandler
4647 * Handles mouse down events.
4650 * @param {jQuery.Event} e Mouse down event
4652 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
4653 if ( this.isDisabled() || e
.which
!== 1 ) {
4656 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4657 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4658 // reliably remove the pressed class
4659 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler
);
4660 // Prevent change of focus unless specifically configured otherwise
4661 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
4667 * Handles mouse up events.
4670 * @param {jQuery.Event} e Mouse up event
4672 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp = function ( e
) {
4673 if ( this.isDisabled() || e
.which
!== 1 ) {
4676 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4677 // Stop listening for mouseup, since we only needed this once
4678 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler
);
4682 * Handles mouse click events.
4685 * @param {jQuery.Event} e Mouse click event
4688 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
4689 if ( !this.isDisabled() && e
.which
=== 1 ) {
4690 if ( this.emit( 'click' ) ) {
4697 * Handles key down events.
4700 * @param {jQuery.Event} e Key down event
4702 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
4703 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4706 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4707 // Run the keyup handler no matter where the key is when the button is let go, so we can
4708 // reliably remove the pressed class
4709 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler
);
4713 * Handles key up events.
4716 * @param {jQuery.Event} e Key up event
4718 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyUp = function ( e
) {
4719 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4722 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4723 // Stop listening for keyup, since we only needed this once
4724 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler
);
4728 * Handles key press events.
4731 * @param {jQuery.Event} e Key press event
4734 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
4735 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
4736 if ( this.emit( 'click' ) ) {
4743 * Check if button has a frame.
4745 * @return {boolean} Button is framed
4747 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
4752 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4754 * @param {boolean} [framed] Make button framed, omit to toggle
4757 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
4758 framed
= framed
=== undefined ? !this.framed
: !!framed
;
4759 if ( framed
!== this.framed
) {
4760 this.framed
= framed
;
4762 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
4763 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
4764 this.updateThemeClasses();
4771 * Set the button's active state.
4773 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4774 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4775 * for other button types.
4777 * @param {boolean} value Make button active
4780 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
4781 this.active
= !!value
;
4782 this.$element
.toggleClass( 'oo-ui-buttonElement-active', this.active
);
4787 * Check if the button is active
4789 * @return {boolean} The button is active
4791 OO
.ui
.mixin
.ButtonElement
.prototype.isActive = function () {
4796 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4797 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4798 * items from the group is done through the interface the class provides.
4799 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4801 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4807 * @param {Object} [config] Configuration options
4808 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4809 * is omitted, the group element will use a generated `<div>`.
4811 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
4812 // Configuration initialization
4813 config
= config
|| {};
4818 this.aggregateItemEvents
= {};
4821 this.setGroupElement( config
.$group
|| $( '<div>' ) );
4827 * Set the group element.
4829 * If an element is already set, items will be moved to the new element.
4831 * @param {jQuery} $group Element to use as group
4833 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
4836 this.$group
= $group
;
4837 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4838 this.$group
.append( this.items
[ i
].$element
);
4843 * Check if a group contains no items.
4845 * @return {boolean} Group is empty
4847 OO
.ui
.mixin
.GroupElement
.prototype.isEmpty = function () {
4848 return !this.items
.length
;
4852 * Get all items in the group.
4854 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4855 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4858 * @return {OO.ui.Element[]} An array of items.
4860 OO
.ui
.mixin
.GroupElement
.prototype.getItems = function () {
4861 return this.items
.slice( 0 );
4865 * Get an item by its data.
4867 * Only the first item with matching data will be returned. To return all matching items,
4868 * use the #getItemsFromData method.
4870 * @param {Object} data Item data to search for
4871 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4873 OO
.ui
.mixin
.GroupElement
.prototype.getItemFromData = function ( data
) {
4875 hash
= OO
.getHash( data
);
4877 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4878 item
= this.items
[ i
];
4879 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4888 * Get items by their data.
4890 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4892 * @param {Object} data Item data to search for
4893 * @return {OO.ui.Element[]} Items with equivalent data
4895 OO
.ui
.mixin
.GroupElement
.prototype.getItemsFromData = function ( data
) {
4897 hash
= OO
.getHash( data
),
4900 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4901 item
= this.items
[ i
];
4902 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4911 * Aggregate the events emitted by the group.
4913 * When events are aggregated, the group will listen to all contained items for the event,
4914 * and then emit the event under a new name. The new event will contain an additional leading
4915 * parameter containing the item that emitted the original event. Other arguments emitted from
4916 * the original event are passed through.
4918 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4919 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4920 * A `null` value will remove aggregated events.
4922 * @throws {Error} An error is thrown if aggregation already exists.
4924 OO
.ui
.mixin
.GroupElement
.prototype.aggregate = function ( events
) {
4925 var i
, len
, item
, add
, remove
, itemEvent
, groupEvent
;
4927 for ( itemEvent
in events
) {
4928 groupEvent
= events
[ itemEvent
];
4930 // Remove existing aggregated event
4931 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4932 // Don't allow duplicate aggregations
4934 throw new Error( 'Duplicate item event aggregation for ' + itemEvent
);
4936 // Remove event aggregation from existing items
4937 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4938 item
= this.items
[ i
];
4939 if ( item
.connect
&& item
.disconnect
) {
4941 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4942 item
.disconnect( this, remove
);
4945 // Prevent future items from aggregating event
4946 delete this.aggregateItemEvents
[ itemEvent
];
4949 // Add new aggregate event
4951 // Make future items aggregate event
4952 this.aggregateItemEvents
[ itemEvent
] = groupEvent
;
4953 // Add event aggregation to existing items
4954 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4955 item
= this.items
[ i
];
4956 if ( item
.connect
&& item
.disconnect
) {
4958 add
[ itemEvent
] = [ 'emit', groupEvent
, item
];
4959 item
.connect( this, add
);
4967 * Add items to the group.
4969 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4970 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4972 * @param {OO.ui.Element[]} items An array of items to add to the group
4973 * @param {number} [index] Index of the insertion point
4976 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
4977 var i
, len
, item
, event
, events
, currentIndex
,
4980 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4983 // Check if item exists then remove it first, effectively "moving" it
4984 currentIndex
= this.items
.indexOf( item
);
4985 if ( currentIndex
>= 0 ) {
4986 this.removeItems( [ item
] );
4987 // Adjust index to compensate for removal
4988 if ( currentIndex
< index
) {
4993 if ( item
.connect
&& item
.disconnect
&& !$.isEmptyObject( this.aggregateItemEvents
) ) {
4995 for ( event
in this.aggregateItemEvents
) {
4996 events
[ event
] = [ 'emit', this.aggregateItemEvents
[ event
], item
];
4998 item
.connect( this, events
);
5000 item
.setElementGroup( this );
5001 itemElements
.push( item
.$element
.get( 0 ) );
5004 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
5005 this.$group
.append( itemElements
);
5006 this.items
.push
.apply( this.items
, items
);
5007 } else if ( index
=== 0 ) {
5008 this.$group
.prepend( itemElements
);
5009 this.items
.unshift
.apply( this.items
, items
);
5011 this.items
[ index
].$element
.before( itemElements
);
5012 this.items
.splice
.apply( this.items
, [ index
, 0 ].concat( items
) );
5019 * Remove the specified items from a group.
5021 * Removed items are detached (not removed) from the DOM so that they may be reused.
5022 * To remove all items from a group, you may wish to use the #clearItems method instead.
5024 * @param {OO.ui.Element[]} items An array of items to remove
5027 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
5028 var i
, len
, item
, index
, remove
, itemEvent
;
5030 // Remove specific items
5031 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
5033 index
= this.items
.indexOf( item
);
5034 if ( index
!== -1 ) {
5036 item
.connect
&& item
.disconnect
&&
5037 !$.isEmptyObject( this.aggregateItemEvents
)
5040 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
5041 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
5043 item
.disconnect( this, remove
);
5045 item
.setElementGroup( null );
5046 this.items
.splice( index
, 1 );
5047 item
.$element
.detach();
5055 * Clear all items from the group.
5057 * Cleared items are detached from the DOM, not removed, so that they may be reused.
5058 * To remove only a subset of items from a group, use the #removeItems method.
5062 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
5063 var i
, len
, item
, remove
, itemEvent
;
5066 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5067 item
= this.items
[ i
];
5069 item
.connect
&& item
.disconnect
&&
5070 !$.isEmptyObject( this.aggregateItemEvents
)
5073 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
5074 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
5076 item
.disconnect( this, remove
);
5078 item
.setElementGroup( null );
5079 item
.$element
.detach();
5087 * DraggableElement is a mixin class used to create elements that can be clicked
5088 * and dragged by a mouse to a new position within a group. This class must be used
5089 * in conjunction with OO.ui.mixin.DraggableGroupElement, which provides a container for
5090 * the draggable elements.
5097 OO
.ui
.mixin
.DraggableElement
= function OoUiMixinDraggableElement() {
5101 // Initialize and events
5103 .attr( 'draggable', true )
5104 .addClass( 'oo-ui-draggableElement' )
5106 dragstart
: this.onDragStart
.bind( this ),
5107 dragover
: this.onDragOver
.bind( this ),
5108 dragend
: this.onDragEnd
.bind( this ),
5109 drop
: this.onDrop
.bind( this )
5113 OO
.initClass( OO
.ui
.mixin
.DraggableElement
);
5120 * A dragstart event is emitted when the user clicks and begins dragging an item.
5121 * @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse.
5126 * A dragend event is emitted when the user drags an item and releases the mouse,
5127 * thus terminating the drag operation.
5132 * A drop event is emitted when the user drags an item and then releases the mouse button
5133 * over a valid target.
5136 /* Static Properties */
5139 * @inheritdoc OO.ui.mixin.ButtonElement
5141 OO
.ui
.mixin
.DraggableElement
.static.cancelButtonMouseDownEvents
= false;
5146 * Respond to dragstart event.
5149 * @param {jQuery.Event} event jQuery event
5152 OO
.ui
.mixin
.DraggableElement
.prototype.onDragStart = function ( e
) {
5153 var dataTransfer
= e
.originalEvent
.dataTransfer
;
5154 // Define drop effect
5155 dataTransfer
.dropEffect
= 'none';
5156 dataTransfer
.effectAllowed
= 'move';
5158 // We must set up a dataTransfer data property or Firefox seems to
5159 // ignore the fact the element is draggable.
5161 dataTransfer
.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
5163 // The above is only for Firefox. Move on if it fails.
5165 // Add dragging class
5166 this.$element
.addClass( 'oo-ui-draggableElement-dragging' );
5168 this.emit( 'dragstart', this );
5173 * Respond to dragend event.
5178 OO
.ui
.mixin
.DraggableElement
.prototype.onDragEnd = function () {
5179 this.$element
.removeClass( 'oo-ui-draggableElement-dragging' );
5180 this.emit( 'dragend' );
5184 * Handle drop event.
5187 * @param {jQuery.Event} event jQuery event
5190 OO
.ui
.mixin
.DraggableElement
.prototype.onDrop = function ( e
) {
5192 this.emit( 'drop', e
);
5196 * In order for drag/drop to work, the dragover event must
5197 * return false and stop propogation.
5201 OO
.ui
.mixin
.DraggableElement
.prototype.onDragOver = function ( e
) {
5207 * Store it in the DOM so we can access from the widget drag event
5210 * @param {number} Item index
5212 OO
.ui
.mixin
.DraggableElement
.prototype.setIndex = function ( index
) {
5213 if ( this.index
!== index
) {
5215 this.$element
.data( 'index', index
);
5223 * @return {number} Item index
5225 OO
.ui
.mixin
.DraggableElement
.prototype.getIndex = function () {
5230 * DraggableGroupElement is a mixin class used to create a group element to
5231 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
5232 * The class is used with OO.ui.mixin.DraggableElement.
5236 * @mixins OO.ui.mixin.GroupElement
5239 * @param {Object} [config] Configuration options
5240 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
5241 * should match the layout of the items. Items displayed in a single row
5242 * or in several rows should use horizontal orientation. The vertical orientation should only be
5243 * used when the items are displayed in a single column. Defaults to 'vertical'
5245 OO
.ui
.mixin
.DraggableGroupElement
= function OoUiMixinDraggableGroupElement( config
) {
5246 // Configuration initialization
5247 config
= config
|| {};
5249 // Parent constructor
5250 OO
.ui
.mixin
.GroupElement
.call( this, config
);
5253 this.orientation
= config
.orientation
|| 'vertical';
5254 this.dragItem
= null;
5255 this.itemDragOver
= null;
5257 this.sideInsertion
= '';
5261 dragstart
: 'itemDragStart',
5262 dragend
: 'itemDragEnd',
5265 this.connect( this, {
5266 itemDragStart
: 'onItemDragStart',
5267 itemDrop
: 'onItemDrop',
5268 itemDragEnd
: 'onItemDragEnd'
5271 dragover
: this.onDragOver
.bind( this ),
5272 dragleave
: this.onDragLeave
.bind( this )
5276 if ( Array
.isArray( config
.items
) ) {
5277 this.addItems( config
.items
);
5279 this.$placeholder
= $( '<div>' )
5280 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
5282 .addClass( 'oo-ui-draggableGroupElement' )
5283 .append( this.$status
)
5284 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation
=== 'horizontal' )
5285 .prepend( this.$placeholder
);
5289 OO
.mixinClass( OO
.ui
.mixin
.DraggableGroupElement
, OO
.ui
.mixin
.GroupElement
);
5294 * A 'reorder' event is emitted when the order of items in the group changes.
5297 * @param {OO.ui.mixin.DraggableElement} item Reordered item
5298 * @param {number} [newIndex] New index for the item
5304 * Respond to item drag start event
5307 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5309 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDragStart = function ( item
) {
5312 // Map the index of each object
5313 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5314 this.items
[ i
].setIndex( i
);
5317 if ( this.orientation
=== 'horizontal' ) {
5318 // Set the height of the indicator
5319 this.$placeholder
.css( {
5320 height
: item
.$element
.outerHeight(),
5324 // Set the width of the indicator
5325 this.$placeholder
.css( {
5327 width
: item
.$element
.outerWidth()
5330 this.setDragItem( item
);
5334 * Respond to item drag end event
5338 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDragEnd = function () {
5339 this.unsetDragItem();
5344 * Handle drop event and switch the order of the items accordingly
5347 * @param {OO.ui.mixin.DraggableElement} item Dropped item
5350 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDrop = function ( item
) {
5351 var toIndex
= item
.getIndex();
5352 // Check if the dropped item is from the current group
5353 // TODO: Figure out a way to configure a list of legally droppable
5354 // elements even if they are not yet in the list
5355 if ( this.getDragItem() ) {
5356 // If the insertion point is 'after', the insertion index
5357 // is shifted to the right (or to the left in RTL, hence 'after')
5358 if ( this.sideInsertion
=== 'after' ) {
5361 // Emit change event
5362 this.emit( 'reorder', this.getDragItem(), toIndex
);
5364 this.unsetDragItem();
5365 // Return false to prevent propogation
5370 * Handle dragleave event.
5374 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onDragLeave = function () {
5375 // This means the item was dragged outside the widget
5378 .addClass( 'oo-ui-element-hidden' );
5382 * Respond to dragover event
5385 * @param {jQuery.Event} event Event details
5387 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onDragOver = function ( e
) {
5388 var dragOverObj
, $optionWidget
, itemOffset
, itemMidpoint
, itemBoundingRect
,
5389 itemSize
, cssOutput
, dragPosition
, itemIndex
, itemPosition
,
5390 clientX
= e
.originalEvent
.clientX
,
5391 clientY
= e
.originalEvent
.clientY
;
5393 // Get the OptionWidget item we are dragging over
5394 dragOverObj
= this.getElementDocument().elementFromPoint( clientX
, clientY
);
5395 $optionWidget
= $( dragOverObj
).closest( '.oo-ui-draggableElement' );
5396 if ( $optionWidget
[ 0 ] ) {
5397 itemOffset
= $optionWidget
.offset();
5398 itemBoundingRect
= $optionWidget
[ 0 ].getBoundingClientRect();
5399 itemPosition
= $optionWidget
.position();
5400 itemIndex
= $optionWidget
.data( 'index' );
5405 this.isDragging() &&
5406 itemIndex
!== this.getDragItem().getIndex()
5408 if ( this.orientation
=== 'horizontal' ) {
5409 // Calculate where the mouse is relative to the item width
5410 itemSize
= itemBoundingRect
.width
;
5411 itemMidpoint
= itemBoundingRect
.left
+ itemSize
/ 2;
5412 dragPosition
= clientX
;
5413 // Which side of the item we hover over will dictate
5414 // where the placeholder will appear, on the left or
5417 left
: dragPosition
< itemMidpoint
? itemPosition
.left
: itemPosition
.left
+ itemSize
,
5418 top
: itemPosition
.top
5421 // Calculate where the mouse is relative to the item height
5422 itemSize
= itemBoundingRect
.height
;
5423 itemMidpoint
= itemBoundingRect
.top
+ itemSize
/ 2;
5424 dragPosition
= clientY
;
5425 // Which side of the item we hover over will dictate
5426 // where the placeholder will appear, on the top or
5429 top
: dragPosition
< itemMidpoint
? itemPosition
.top
: itemPosition
.top
+ itemSize
,
5430 left
: itemPosition
.left
5433 // Store whether we are before or after an item to rearrange
5434 // For horizontal layout, we need to account for RTL, as this is flipped
5435 if ( this.orientation
=== 'horizontal' && this.$element
.css( 'direction' ) === 'rtl' ) {
5436 this.sideInsertion
= dragPosition
< itemMidpoint
? 'after' : 'before';
5438 this.sideInsertion
= dragPosition
< itemMidpoint
? 'before' : 'after';
5440 // Add drop indicator between objects
5443 .removeClass( 'oo-ui-element-hidden' );
5445 // This means the item was dragged outside the widget
5448 .addClass( 'oo-ui-element-hidden' );
5455 * Set a dragged item
5457 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5459 OO
.ui
.mixin
.DraggableGroupElement
.prototype.setDragItem = function ( item
) {
5460 this.dragItem
= item
;
5464 * Unset the current dragged item
5466 OO
.ui
.mixin
.DraggableGroupElement
.prototype.unsetDragItem = function () {
5467 this.dragItem
= null;
5468 this.itemDragOver
= null;
5469 this.$placeholder
.addClass( 'oo-ui-element-hidden' );
5470 this.sideInsertion
= '';
5474 * Get the item that is currently being dragged.
5476 * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
5478 OO
.ui
.mixin
.DraggableGroupElement
.prototype.getDragItem = function () {
5479 return this.dragItem
;
5483 * Check if an item in the group is currently being dragged.
5485 * @return {Boolean} Item is being dragged
5487 OO
.ui
.mixin
.DraggableGroupElement
.prototype.isDragging = function () {
5488 return this.getDragItem() !== null;
5492 * IconElement is often mixed into other classes to generate an icon.
5493 * Icons are graphics, about the size of normal text. They are used to aid the user
5494 * in locating a control or to convey information in a space-efficient way. See the
5495 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
5496 * included in the library.
5498 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5504 * @param {Object} [config] Configuration options
5505 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
5506 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
5507 * the icon element be set to an existing icon instead of the one generated by this class, set a
5508 * value using a jQuery selection. For example:
5510 * // Use a <div> tag instead of a <span>
5512 * // Use an existing icon element instead of the one generated by the class
5513 * $icon: this.$element
5514 * // Use an icon element from a child widget
5515 * $icon: this.childwidget.$element
5516 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
5517 * symbolic names. A map is used for i18n purposes and contains a `default` icon
5518 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
5519 * by the user's language.
5521 * Example of an i18n map:
5523 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5524 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
5525 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5526 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
5527 * text. The icon title is displayed when users move the mouse over the icon.
5529 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
5530 // Configuration initialization
5531 config
= config
|| {};
5536 this.iconTitle
= null;
5539 this.setIcon( config
.icon
|| this.constructor.static.icon
);
5540 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
5541 this.setIconElement( config
.$icon
|| $( '<span>' ) );
5546 OO
.initClass( OO
.ui
.mixin
.IconElement
);
5548 /* Static Properties */
5551 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
5552 * for i18n purposes and contains a `default` icon name and additional names keyed by
5553 * language code. The `default` name is used when no icon is keyed by the user's language.
5555 * Example of an i18n map:
5557 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5559 * Note: the static property will be overridden if the #icon configuration is used.
5563 * @property {Object|string}
5565 OO
.ui
.mixin
.IconElement
.static.icon
= null;
5568 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5569 * function that returns title text, or `null` for no title.
5571 * The static property will be overridden if the #iconTitle configuration is used.
5575 * @property {string|Function|null}
5577 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
5582 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5583 * applies to the specified icon element instead of the one created by the class. If an icon
5584 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5585 * and mixin methods will no longer affect the element.
5587 * @param {jQuery} $icon Element to use as icon
5589 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
5592 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
5593 .removeAttr( 'title' );
5597 .addClass( 'oo-ui-iconElement-icon' )
5598 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
5599 if ( this.iconTitle
!== null ) {
5600 this.$icon
.attr( 'title', this.iconTitle
);
5603 this.updateThemeClasses();
5607 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5608 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5611 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5612 * by language code, or `null` to remove the icon.
5615 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
5616 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
5617 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
5619 if ( this.icon
!== icon
) {
5621 if ( this.icon
!== null ) {
5622 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
5624 if ( icon
!== null ) {
5625 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
5631 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
5632 this.updateThemeClasses();
5638 * Set the icon title. Use `null` to remove the title.
5640 * @param {string|Function|null} iconTitle A text string used as the icon title,
5641 * a function that returns title text, or `null` for no title.
5644 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
5645 iconTitle
= typeof iconTitle
=== 'function' ||
5646 ( typeof iconTitle
=== 'string' && iconTitle
.length
) ?
5647 OO
.ui
.resolveMsg( iconTitle
) : null;
5649 if ( this.iconTitle
!== iconTitle
) {
5650 this.iconTitle
= iconTitle
;
5652 if ( this.iconTitle
!== null ) {
5653 this.$icon
.attr( 'title', iconTitle
);
5655 this.$icon
.removeAttr( 'title' );
5664 * Get the symbolic name of the icon.
5666 * @return {string} Icon name
5668 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
5673 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5675 * @return {string} Icon title text
5677 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
5678 return this.iconTitle
;
5682 * IndicatorElement is often mixed into other classes to generate an indicator.
5683 * Indicators are small graphics that are generally used in two ways:
5685 * - To draw attention to the status of an item. For example, an indicator might be
5686 * used to show that an item in a list has errors that need to be resolved.
5687 * - To clarify the function of a control that acts in an exceptional way (a button
5688 * that opens a menu instead of performing an action directly, for example).
5690 * For a list of indicators included in the library, please see the
5691 * [OOjs UI documentation on MediaWiki] [1].
5693 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5699 * @param {Object} [config] Configuration options
5700 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5701 * configuration is omitted, the indicator element will use a generated `<span>`.
5702 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5703 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5705 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5706 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5707 * or a function that returns title text. The indicator title is displayed when users move
5708 * the mouse over the indicator.
5710 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
5711 // Configuration initialization
5712 config
= config
|| {};
5715 this.$indicator
= null;
5716 this.indicator
= null;
5717 this.indicatorTitle
= null;
5720 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
5721 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
5722 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
5727 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
5729 /* Static Properties */
5732 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5733 * The static property will be overridden if the #indicator configuration is used.
5737 * @property {string|null}
5739 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
5742 * A text string used as the indicator title, a function that returns title text, or `null`
5743 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5747 * @property {string|Function|null}
5749 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
5754 * Set the indicator element.
5756 * If an element is already set, it will be cleaned up before setting up the new element.
5758 * @param {jQuery} $indicator Element to use as indicator
5760 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
5761 if ( this.$indicator
) {
5763 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
5764 .removeAttr( 'title' );
5767 this.$indicator
= $indicator
5768 .addClass( 'oo-ui-indicatorElement-indicator' )
5769 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
5770 if ( this.indicatorTitle
!== null ) {
5771 this.$indicator
.attr( 'title', this.indicatorTitle
);
5774 this.updateThemeClasses();
5778 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5780 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5783 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
5784 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
5786 if ( this.indicator
!== indicator
) {
5787 if ( this.$indicator
) {
5788 if ( this.indicator
!== null ) {
5789 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
5791 if ( indicator
!== null ) {
5792 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
5795 this.indicator
= indicator
;
5798 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
5799 this.updateThemeClasses();
5805 * Set the indicator title.
5807 * The title is displayed when a user moves the mouse over the indicator.
5809 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5810 * `null` for no indicator title
5813 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
5814 indicatorTitle
= typeof indicatorTitle
=== 'function' ||
5815 ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ?
5816 OO
.ui
.resolveMsg( indicatorTitle
) : null;
5818 if ( this.indicatorTitle
!== indicatorTitle
) {
5819 this.indicatorTitle
= indicatorTitle
;
5820 if ( this.$indicator
) {
5821 if ( this.indicatorTitle
!== null ) {
5822 this.$indicator
.attr( 'title', indicatorTitle
);
5824 this.$indicator
.removeAttr( 'title' );
5833 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5835 * @return {string} Symbolic name of indicator
5837 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
5838 return this.indicator
;
5842 * Get the indicator title.
5844 * The title is displayed when a user moves the mouse over the indicator.
5846 * @return {string} Indicator title text
5848 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
5849 return this.indicatorTitle
;
5853 * LabelElement is often mixed into other classes to generate a label, which
5854 * helps identify the function of an interface element.
5855 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5857 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5863 * @param {Object} [config] Configuration options
5864 * @cfg {jQuery} [$label] The label element created by the class. If this
5865 * configuration is omitted, the label element will use a generated `<span>`.
5866 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
5867 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
5868 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
5869 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5870 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5871 * The label will be truncated to fit if necessary.
5873 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
5874 // Configuration initialization
5875 config
= config
|| {};
5880 this.autoFitLabel
= config
.autoFitLabel
=== undefined || !!config
.autoFitLabel
;
5883 this.setLabel( config
.label
|| this.constructor.static.label
);
5884 this.setLabelElement( config
.$label
|| $( '<span>' ) );
5889 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
5894 * @event labelChange
5895 * @param {string} value
5898 /* Static Properties */
5901 * The label text. The label can be specified as a plaintext string, a function that will
5902 * produce a string in the future, or `null` for no label. The static value will
5903 * be overridden if a label is specified with the #label config option.
5907 * @property {string|Function|null}
5909 OO
.ui
.mixin
.LabelElement
.static.label
= null;
5914 * Set the label element.
5916 * If an element is already set, it will be cleaned up before setting up the new element.
5918 * @param {jQuery} $label Element to use as label
5920 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
5921 if ( this.$label
) {
5922 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
5925 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
5926 this.setLabelContent( this.label
);
5932 * An empty string will result in the label being hidden. A string containing only whitespace will
5933 * be converted to a single ` `.
5935 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5936 * text; or null for no label
5939 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
5940 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
5941 label
= ( ( typeof label
=== 'string' && label
.length
) || label
instanceof jQuery
|| label
instanceof OO
.ui
.HtmlSnippet
) ? label
: null;
5943 this.$element
.toggleClass( 'oo-ui-labelElement', !!label
);
5945 if ( this.label
!== label
) {
5946 if ( this.$label
) {
5947 this.setLabelContent( label
);
5950 this.emit( 'labelChange' );
5959 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5960 * text; or null for no label
5962 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
5971 OO
.ui
.mixin
.LabelElement
.prototype.fitLabel = function () {
5972 if ( this.$label
&& this.$label
.autoEllipsis
&& this.autoFitLabel
) {
5973 this.$label
.autoEllipsis( { hasSpan
: false, tooltip
: true } );
5980 * Set the content of the label.
5982 * Do not call this method until after the label element has been set by #setLabelElement.
5985 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5986 * text; or null for no label
5988 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
5989 if ( typeof label
=== 'string' ) {
5990 if ( label
.match( /^\s*$/ ) ) {
5991 // Convert whitespace only string to a single non-breaking space
5992 this.$label
.html( ' ' );
5994 this.$label
.text( label
);
5996 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
5997 this.$label
.html( label
.toString() );
5998 } else if ( label
instanceof jQuery
) {
5999 this.$label
.empty().append( label
);
6001 this.$label
.empty();
6006 * LookupElement is a mixin that creates a {@link OO.ui.FloatingMenuSelectWidget menu} of suggested values for
6007 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
6008 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
6009 * from the lookup menu, that value becomes the value of the input field.
6011 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
6012 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
6013 * re-enable lookups.
6015 * See the [OOjs UI demos][1] for an example.
6017 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
6023 * @param {Object} [config] Configuration options
6024 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
6025 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
6026 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
6027 * By default, the lookup menu is not generated and displayed until the user begins to type.
6028 * @cfg {boolean} [highlightFirst=true] Whether the first lookup result should be highlighted (so, that the user can
6029 * take it over into the input with simply pressing return) automatically or not.
6031 OO
.ui
.mixin
.LookupElement
= function OoUiMixinLookupElement( config
) {
6032 // Configuration initialization
6033 config
= $.extend( { highlightFirst
: true }, config
);
6035 // Mixin constructors
6036 OO
.ui
.mixin
.RequestManager
.call( this, config
);
6039 this.$overlay
= config
.$overlay
|| this.$element
;
6040 this.lookupMenu
= new OO
.ui
.FloatingMenuSelectWidget( {
6043 $container
: config
.$container
|| this.$element
6046 this.allowSuggestionsWhenEmpty
= config
.allowSuggestionsWhenEmpty
|| false;
6048 this.lookupsDisabled
= false;
6049 this.lookupInputFocused
= false;
6050 this.lookupHighlightFirstItem
= config
.highlightFirst
;
6054 focus
: this.onLookupInputFocus
.bind( this ),
6055 blur
: this.onLookupInputBlur
.bind( this ),
6056 mousedown
: this.onLookupInputMouseDown
.bind( this )
6058 this.connect( this, { change
: 'onLookupInputChange' } );
6059 this.lookupMenu
.connect( this, {
6060 toggle
: 'onLookupMenuToggle',
6061 choose
: 'onLookupMenuItemChoose'
6065 this.$element
.addClass( 'oo-ui-lookupElement' );
6066 this.lookupMenu
.$element
.addClass( 'oo-ui-lookupElement-menu' );
6067 this.$overlay
.append( this.lookupMenu
.$element
);
6072 OO
.mixinClass( OO
.ui
.mixin
.LookupElement
, OO
.ui
.mixin
.RequestManager
);
6077 * Handle input focus event.
6080 * @param {jQuery.Event} e Input focus event
6082 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputFocus = function () {
6083 this.lookupInputFocused
= true;
6084 this.populateLookupMenu();
6088 * Handle input blur event.
6091 * @param {jQuery.Event} e Input blur event
6093 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputBlur = function () {
6094 this.closeLookupMenu();
6095 this.lookupInputFocused
= false;
6099 * Handle input mouse down event.
6102 * @param {jQuery.Event} e Input mouse down event
6104 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputMouseDown = function () {
6105 // Only open the menu if the input was already focused.
6106 // This way we allow the user to open the menu again after closing it with Esc
6107 // by clicking in the input. Opening (and populating) the menu when initially
6108 // clicking into the input is handled by the focus handler.
6109 if ( this.lookupInputFocused
&& !this.lookupMenu
.isVisible() ) {
6110 this.populateLookupMenu();
6115 * Handle input change event.
6118 * @param {string} value New input value
6120 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputChange = function () {
6121 if ( this.lookupInputFocused
) {
6122 this.populateLookupMenu();
6127 * Handle the lookup menu being shown/hidden.
6130 * @param {boolean} visible Whether the lookup menu is now visible.
6132 OO
.ui
.mixin
.LookupElement
.prototype.onLookupMenuToggle = function ( visible
) {
6134 // When the menu is hidden, abort any active request and clear the menu.
6135 // This has to be done here in addition to closeLookupMenu(), because
6136 // MenuSelectWidget will close itself when the user presses Esc.
6137 this.abortLookupRequest();
6138 this.lookupMenu
.clearItems();
6143 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
6146 * @param {OO.ui.MenuOptionWidget} item Selected item
6148 OO
.ui
.mixin
.LookupElement
.prototype.onLookupMenuItemChoose = function ( item
) {
6149 this.setValue( item
.getData() );
6156 * @return {OO.ui.FloatingMenuSelectWidget}
6158 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenu = function () {
6159 return this.lookupMenu
;
6163 * Disable or re-enable lookups.
6165 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
6167 * @param {boolean} disabled Disable lookups
6169 OO
.ui
.mixin
.LookupElement
.prototype.setLookupsDisabled = function ( disabled
) {
6170 this.lookupsDisabled
= !!disabled
;
6174 * Open the menu. If there are no entries in the menu, this does nothing.
6179 OO
.ui
.mixin
.LookupElement
.prototype.openLookupMenu = function () {
6180 if ( !this.lookupMenu
.isEmpty() ) {
6181 this.lookupMenu
.toggle( true );
6187 * Close the menu, empty it, and abort any pending request.
6192 OO
.ui
.mixin
.LookupElement
.prototype.closeLookupMenu = function () {
6193 this.lookupMenu
.toggle( false );
6194 this.abortLookupRequest();
6195 this.lookupMenu
.clearItems();
6200 * Request menu items based on the input's current value, and when they arrive,
6201 * populate the menu with these items and show the menu.
6203 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
6208 OO
.ui
.mixin
.LookupElement
.prototype.populateLookupMenu = function () {
6210 value
= this.getValue();
6212 if ( this.lookupsDisabled
|| this.isReadOnly() ) {
6216 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
6217 if ( !this.allowSuggestionsWhenEmpty
&& value
=== '' ) {
6218 this.closeLookupMenu();
6219 // Skip population if there is already a request pending for the current value
6220 } else if ( value
!== this.lookupQuery
) {
6221 this.getLookupMenuItems()
6222 .done( function ( items
) {
6223 widget
.lookupMenu
.clearItems();
6224 if ( items
.length
) {
6228 widget
.initializeLookupMenuSelection();
6230 widget
.lookupMenu
.toggle( false );
6233 .fail( function () {
6234 widget
.lookupMenu
.clearItems();
6242 * Highlight the first selectable item in the menu, if configured.
6247 OO
.ui
.mixin
.LookupElement
.prototype.initializeLookupMenuSelection = function () {
6248 if ( this.lookupHighlightFirstItem
&& !this.lookupMenu
.getSelectedItem() ) {
6249 this.lookupMenu
.highlightItem( this.lookupMenu
.getFirstSelectableItem() );
6254 * Get lookup menu items for the current query.
6257 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
6258 * the done event. If the request was aborted to make way for a subsequent request, this promise
6259 * will not be rejected: it will remain pending forever.
6261 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenuItems = function () {
6262 return this.getRequestData().then( function ( data
) {
6263 return this.getLookupMenuOptionsFromData( data
);
6268 * Abort the currently pending lookup request, if any.
6272 OO
.ui
.mixin
.LookupElement
.prototype.abortLookupRequest = function () {
6273 this.abortRequest();
6277 * Get a new request object of the current lookup query value.
6282 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
6284 OO
.ui
.mixin
.LookupElement
.prototype.getLookupRequest
= null;
6287 * Pre-process data returned by the request from #getLookupRequest.
6289 * The return value of this function will be cached, and any further queries for the given value
6290 * will use the cache rather than doing API requests.
6295 * @param {Mixed} response Response from server
6296 * @return {Mixed} Cached result data
6298 OO
.ui
.mixin
.LookupElement
.prototype.getLookupCacheDataFromResponse
= null;
6301 * Get a list of menu option widgets from the (possibly cached) data returned by
6302 * #getLookupCacheDataFromResponse.
6307 * @param {Mixed} data Cached result data, usually an array
6308 * @return {OO.ui.MenuOptionWidget[]} Menu items
6310 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenuOptionsFromData
= null;
6313 * Set the read-only state of the widget.
6315 * This will also disable/enable the lookups functionality.
6317 * @param {boolean} readOnly Make input read-only
6320 OO
.ui
.mixin
.LookupElement
.prototype.setReadOnly = function ( readOnly
) {
6322 // Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget
6323 OO
.ui
.TextInputWidget
.prototype.setReadOnly
.call( this, readOnly
);
6325 // During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor
6326 if ( this.isReadOnly() && this.lookupMenu
) {
6327 this.closeLookupMenu();
6334 * @inheritdoc OO.ui.mixin.RequestManager
6336 OO
.ui
.mixin
.LookupElement
.prototype.getRequestQuery = function () {
6337 return this.getValue();
6341 * @inheritdoc OO.ui.mixin.RequestManager
6343 OO
.ui
.mixin
.LookupElement
.prototype.getRequest = function () {
6344 return this.getLookupRequest();
6348 * @inheritdoc OO.ui.mixin.RequestManager
6350 OO
.ui
.mixin
.LookupElement
.prototype.getRequestCacheDataFromResponse = function ( response
) {
6351 return this.getLookupCacheDataFromResponse( response
);
6355 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
6356 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
6357 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
6358 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
6364 * @param {Object} [config] Configuration options
6365 * @cfg {Object} [popup] Configuration to pass to popup
6366 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
6368 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
6369 // Configuration initialization
6370 config
= config
|| {};
6373 this.popup
= new OO
.ui
.PopupWidget( $.extend(
6374 { autoClose
: true },
6376 { $autoCloseIgnore
: this.$element
}
6385 * @return {OO.ui.PopupWidget} Popup widget
6387 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
6392 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
6393 * additional functionality to an element created by another class. The class provides
6394 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
6395 * which are used to customize the look and feel of a widget to better describe its
6396 * importance and functionality.
6398 * The library currently contains the following styling flags for general use:
6400 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
6401 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
6402 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
6404 * The flags affect the appearance of the buttons:
6407 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
6408 * var button1 = new OO.ui.ButtonWidget( {
6409 * label: 'Constructive',
6410 * flags: 'constructive'
6412 * var button2 = new OO.ui.ButtonWidget( {
6413 * label: 'Destructive',
6414 * flags: 'destructive'
6416 * var button3 = new OO.ui.ButtonWidget( {
6417 * label: 'Progressive',
6418 * flags: 'progressive'
6420 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
6422 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
6423 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6425 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6431 * @param {Object} [config] Configuration options
6432 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
6433 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
6434 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6435 * @cfg {jQuery} [$flagged] The flagged element. By default,
6436 * the flagged functionality is applied to the element created by the class ($element).
6437 * If a different element is specified, the flagged functionality will be applied to it instead.
6439 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
6440 // Configuration initialization
6441 config
= config
|| {};
6445 this.$flagged
= null;
6448 this.setFlags( config
.flags
);
6449 this.setFlaggedElement( config
.$flagged
|| this.$element
);
6456 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
6457 * parameter contains the name of each modified flag and indicates whether it was
6460 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
6461 * that the flag was added, `false` that the flag was removed.
6467 * Set the flagged element.
6469 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
6470 * If an element is already set, the method will remove the mixin’s effect on that element.
6472 * @param {jQuery} $flagged Element that should be flagged
6474 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
6475 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
6476 return 'oo-ui-flaggedElement-' + flag
;
6479 if ( this.$flagged
) {
6480 this.$flagged
.removeClass( classNames
);
6483 this.$flagged
= $flagged
.addClass( classNames
);
6487 * Check if the specified flag is set.
6489 * @param {string} flag Name of flag
6490 * @return {boolean} The flag is set
6492 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
6493 // This may be called before the constructor, thus before this.flags is set
6494 return this.flags
&& ( flag
in this.flags
);
6498 * Get the names of all flags set.
6500 * @return {string[]} Flag names
6502 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
6503 // This may be called before the constructor, thus before this.flags is set
6504 return Object
.keys( this.flags
|| {} );
6513 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
6514 var flag
, className
,
6517 classPrefix
= 'oo-ui-flaggedElement-';
6519 for ( flag
in this.flags
) {
6520 className
= classPrefix
+ flag
;
6521 changes
[ flag
] = false;
6522 delete this.flags
[ flag
];
6523 remove
.push( className
);
6526 if ( this.$flagged
) {
6527 this.$flagged
.removeClass( remove
.join( ' ' ) );
6530 this.updateThemeClasses();
6531 this.emit( 'flag', changes
);
6537 * Add one or more flags.
6539 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
6540 * or an object keyed by flag name with a boolean value that indicates whether the flag should
6541 * be added (`true`) or removed (`false`).
6545 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
6546 var i
, len
, flag
, className
,
6550 classPrefix
= 'oo-ui-flaggedElement-';
6552 if ( typeof flags
=== 'string' ) {
6553 className
= classPrefix
+ flags
;
6555 if ( !this.flags
[ flags
] ) {
6556 this.flags
[ flags
] = true;
6557 add
.push( className
);
6559 } else if ( Array
.isArray( flags
) ) {
6560 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
6562 className
= classPrefix
+ flag
;
6564 if ( !this.flags
[ flag
] ) {
6565 changes
[ flag
] = true;
6566 this.flags
[ flag
] = true;
6567 add
.push( className
);
6570 } else if ( OO
.isPlainObject( flags
) ) {
6571 for ( flag
in flags
) {
6572 className
= classPrefix
+ flag
;
6573 if ( flags
[ flag
] ) {
6575 if ( !this.flags
[ flag
] ) {
6576 changes
[ flag
] = true;
6577 this.flags
[ flag
] = true;
6578 add
.push( className
);
6582 if ( this.flags
[ flag
] ) {
6583 changes
[ flag
] = false;
6584 delete this.flags
[ flag
];
6585 remove
.push( className
);
6591 if ( this.$flagged
) {
6593 .addClass( add
.join( ' ' ) )
6594 .removeClass( remove
.join( ' ' ) );
6597 this.updateThemeClasses();
6598 this.emit( 'flag', changes
);
6604 * TitledElement is mixed into other classes to provide a `title` attribute.
6605 * Titles are rendered by the browser and are made visible when the user moves
6606 * the mouse over the element. Titles are not visible on touch devices.
6609 * // TitledElement provides a 'title' attribute to the
6610 * // ButtonWidget class
6611 * var button = new OO.ui.ButtonWidget( {
6612 * label: 'Button with Title',
6613 * title: 'I am a button'
6615 * $( 'body' ).append( button.$element );
6621 * @param {Object} [config] Configuration options
6622 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6623 * If this config is omitted, the title functionality is applied to $element, the
6624 * element created by the class.
6625 * @cfg {string|Function} [title] The title text or a function that returns text. If
6626 * this config is omitted, the value of the {@link #static-title static title} property is used.
6628 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
6629 // Configuration initialization
6630 config
= config
|| {};
6633 this.$titled
= null;
6637 this.setTitle( config
.title
|| this.constructor.static.title
);
6638 this.setTitledElement( config
.$titled
|| this.$element
);
6643 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
6645 /* Static Properties */
6648 * The title text, a function that returns text, or `null` for no title. The value of the static property
6649 * is overridden if the #title config option is used.
6653 * @property {string|Function|null}
6655 OO
.ui
.mixin
.TitledElement
.static.title
= null;
6660 * Set the titled element.
6662 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6663 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6665 * @param {jQuery} $titled Element that should use the 'titled' functionality
6667 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
6668 if ( this.$titled
) {
6669 this.$titled
.removeAttr( 'title' );
6672 this.$titled
= $titled
;
6674 this.$titled
.attr( 'title', this.title
);
6681 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6684 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
6685 title
= typeof title
=== 'function' ? OO
.ui
.resolveMsg( title
) : title
;
6686 title
= ( typeof title
=== 'string' && title
.length
) ? title
: null;
6688 if ( this.title
!== title
) {
6689 if ( this.$titled
) {
6690 if ( title
!== null ) {
6691 this.$titled
.attr( 'title', title
);
6693 this.$titled
.removeAttr( 'title' );
6705 * @return {string} Title string
6707 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
6712 * Element that can be automatically clipped to visible boundaries.
6714 * Whenever the element's natural height changes, you have to call
6715 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
6716 * clipping correctly.
6718 * The dimensions of #$clippableContainer will be compared to the boundaries of the
6719 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
6720 * then #$clippable will be given a fixed reduced height and/or width and will be made
6721 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
6722 * but you can build a static footer by setting #$clippableContainer to an element that contains
6723 * #$clippable and the footer.
6729 * @param {Object} [config] Configuration options
6730 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
6731 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
6732 * omit to use #$clippable
6734 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
6735 // Configuration initialization
6736 config
= config
|| {};
6739 this.$clippable
= null;
6740 this.$clippableContainer
= null;
6741 this.clipping
= false;
6742 this.clippedHorizontally
= false;
6743 this.clippedVertically
= false;
6744 this.$clippableScrollableContainer
= null;
6745 this.$clippableScroller
= null;
6746 this.$clippableWindow
= null;
6747 this.idealWidth
= null;
6748 this.idealHeight
= null;
6749 this.onClippableScrollHandler
= this.clip
.bind( this );
6750 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
6753 if ( config
.$clippableContainer
) {
6754 this.setClippableContainer( config
.$clippableContainer
);
6756 this.setClippableElement( config
.$clippable
|| this.$element
);
6762 * Set clippable element.
6764 * If an element is already set, it will be cleaned up before setting up the new element.
6766 * @param {jQuery} $clippable Element to make clippable
6768 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
6769 if ( this.$clippable
) {
6770 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
6771 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6772 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6775 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
6780 * Set clippable container.
6782 * This is the container that will be measured when deciding whether to clip. When clipping,
6783 * #$clippable will be resized in order to keep the clippable container fully visible.
6785 * If the clippable container is unset, #$clippable will be used.
6787 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
6789 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableContainer = function ( $clippableContainer
) {
6790 this.$clippableContainer
= $clippableContainer
;
6791 if ( this.$clippable
) {
6799 * Do not turn clipping on until after the element is attached to the DOM and visible.
6801 * @param {boolean} [clipping] Enable clipping, omit to toggle
6804 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
6805 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
6807 if ( this.clipping
!== clipping
) {
6808 this.clipping
= clipping
;
6810 this.$clippableScrollableContainer
= $( this.getClosestScrollableElementContainer() );
6811 // If the clippable container is the root, we have to listen to scroll events and check
6812 // jQuery.scrollTop on the window because of browser inconsistencies
6813 this.$clippableScroller
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
6814 $( OO
.ui
.Element
.static.getWindow( this.$clippableScrollableContainer
) ) :
6815 this.$clippableScrollableContainer
;
6816 this.$clippableScroller
.on( 'scroll', this.onClippableScrollHandler
);
6817 this.$clippableWindow
= $( this.getElementWindow() )
6818 .on( 'resize', this.onClippableWindowResizeHandler
);
6819 // Initial clip after visible
6822 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6823 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6825 this.$clippableScrollableContainer
= null;
6826 this.$clippableScroller
.off( 'scroll', this.onClippableScrollHandler
);
6827 this.$clippableScroller
= null;
6828 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
6829 this.$clippableWindow
= null;
6837 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6839 * @return {boolean} Element will be clipped to the visible area
6841 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
6842 return this.clipping
;
6846 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6848 * @return {boolean} Part of the element is being clipped
6850 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
6851 return this.clippedHorizontally
|| this.clippedVertically
;
6855 * Check if the right of the element is being clipped by the nearest scrollable container.
6857 * @return {boolean} Part of the element is being clipped
6859 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
6860 return this.clippedHorizontally
;
6864 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6866 * @return {boolean} Part of the element is being clipped
6868 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
6869 return this.clippedVertically
;
6873 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6875 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6876 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6878 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
6879 this.idealWidth
= width
;
6880 this.idealHeight
= height
;
6882 if ( !this.clipping
) {
6883 // Update dimensions
6884 this.$clippable
.css( { width
: width
, height
: height
} );
6886 // While clipping, idealWidth and idealHeight are not considered
6890 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6891 * the element's natural height changes.
6893 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6894 * overlapped by, the visible area of the nearest scrollable container.
6898 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
6899 var $container
, extraHeight
, extraWidth
, ccOffset
,
6900 $scrollableContainer
, scOffset
, scHeight
, scWidth
,
6901 ccWidth
, scrollerIsWindow
, scrollTop
, scrollLeft
,
6902 desiredWidth
, desiredHeight
, allotedWidth
, allotedHeight
,
6903 naturalWidth
, naturalHeight
, clipWidth
, clipHeight
,
6904 buffer
= 7; // Chosen by fair dice roll
6906 if ( !this.clipping
) {
6907 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
6911 $container
= this.$clippableContainer
|| this.$clippable
;
6912 extraHeight
= $container
.outerHeight() - this.$clippable
.outerHeight();
6913 extraWidth
= $container
.outerWidth() - this.$clippable
.outerWidth();
6914 ccOffset
= $container
.offset();
6915 $scrollableContainer
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
6916 this.$clippableWindow
: this.$clippableScrollableContainer
;
6917 scOffset
= $scrollableContainer
.offset() || { top
: 0, left
: 0 };
6918 scHeight
= $scrollableContainer
.innerHeight() - buffer
;
6919 scWidth
= $scrollableContainer
.innerWidth() - buffer
;
6920 ccWidth
= $container
.outerWidth() + buffer
;
6921 scrollerIsWindow
= this.$clippableScroller
[ 0 ] === this.$clippableWindow
[ 0 ];
6922 scrollTop
= scrollerIsWindow
? this.$clippableScroller
.scrollTop() : 0;
6923 scrollLeft
= scrollerIsWindow
? this.$clippableScroller
.scrollLeft() : 0;
6924 desiredWidth
= ccOffset
.left
< 0 ?
6925 ccWidth
+ ccOffset
.left
:
6926 ( scOffset
.left
+ scrollLeft
+ scWidth
) - ccOffset
.left
;
6927 desiredHeight
= ( scOffset
.top
+ scrollTop
+ scHeight
) - ccOffset
.top
;
6928 allotedWidth
= desiredWidth
- extraWidth
;
6929 allotedHeight
= desiredHeight
- extraHeight
;
6930 naturalWidth
= this.$clippable
.prop( 'scrollWidth' );
6931 naturalHeight
= this.$clippable
.prop( 'scrollHeight' );
6932 clipWidth
= allotedWidth
< naturalWidth
;
6933 clipHeight
= allotedHeight
< naturalHeight
;
6936 this.$clippable
.css( { overflowX
: 'scroll', width
: Math
.max( 0, allotedWidth
) } );
6938 this.$clippable
.css( { width
: this.idealWidth
? this.idealWidth
- extraWidth
: '', overflowX
: '' } );
6941 this.$clippable
.css( { overflowY
: 'scroll', height
: Math
.max( 0, allotedHeight
) } );
6943 this.$clippable
.css( { height
: this.idealHeight
? this.idealHeight
- extraHeight
: '', overflowY
: '' } );
6946 // If we stopped clipping in at least one of the dimensions
6947 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
6948 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6951 this.clippedHorizontally
= clipWidth
;
6952 this.clippedVertically
= clipHeight
;
6958 * Element that will stick under a specified container, even when it is inserted elsewhere in the
6959 * document (for example, in a OO.ui.Window's $overlay).
6961 * The elements's position is automatically calculated and maintained when window is resized or the
6962 * page is scrolled. If you reposition the container manually, you have to call #position to make
6963 * sure the element is still placed correctly.
6965 * As positioning is only possible when both the element and the container are attached to the DOM
6966 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
6967 * the #toggle method to display a floating popup, for example.
6973 * @param {Object} [config] Configuration options
6974 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
6975 * @cfg {jQuery} [$floatableContainer] Node to position below
6977 OO
.ui
.mixin
.FloatableElement
= function OoUiMixinFloatableElement( config
) {
6978 // Configuration initialization
6979 config
= config
|| {};
6982 this.$floatable
= null;
6983 this.$floatableContainer
= null;
6984 this.$floatableWindow
= null;
6985 this.$floatableClosestScrollable
= null;
6986 this.onFloatableScrollHandler
= this.position
.bind( this );
6987 this.onFloatableWindowResizeHandler
= this.position
.bind( this );
6990 this.setFloatableContainer( config
.$floatableContainer
);
6991 this.setFloatableElement( config
.$floatable
|| this.$element
);
6997 * Set floatable element.
6999 * If an element is already set, it will be cleaned up before setting up the new element.
7001 * @param {jQuery} $floatable Element to make floatable
7003 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableElement = function ( $floatable
) {
7004 if ( this.$floatable
) {
7005 this.$floatable
.removeClass( 'oo-ui-floatableElement-floatable' );
7006 this.$floatable
.css( { left
: '', top
: '' } );
7009 this.$floatable
= $floatable
.addClass( 'oo-ui-floatableElement-floatable' );
7014 * Set floatable container.
7016 * The element will be always positioned under the specified container.
7018 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
7020 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableContainer = function ( $floatableContainer
) {
7021 this.$floatableContainer
= $floatableContainer
;
7022 if ( this.$floatable
) {
7028 * Toggle positioning.
7030 * Do not turn positioning on until after the element is attached to the DOM and visible.
7032 * @param {boolean} [positioning] Enable positioning, omit to toggle
7035 OO
.ui
.mixin
.FloatableElement
.prototype.togglePositioning = function ( positioning
) {
7036 var closestScrollableOfContainer
, closestScrollableOfFloatable
;
7038 positioning
= positioning
=== undefined ? !this.positioning
: !!positioning
;
7040 if ( this.positioning
!== positioning
) {
7041 this.positioning
= positioning
;
7043 closestScrollableOfContainer
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatableContainer
[ 0 ] );
7044 closestScrollableOfFloatable
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatable
[ 0 ] );
7045 if ( closestScrollableOfContainer
!== closestScrollableOfFloatable
) {
7046 // If the scrollable is the root, we have to listen to scroll events
7047 // on the window because of browser inconsistencies (or do we? someone should verify this)
7048 if ( $( closestScrollableOfContainer
).is( 'html, body' ) ) {
7049 closestScrollableOfContainer
= OO
.ui
.Element
.static.getWindow( closestScrollableOfContainer
);
7053 if ( positioning
) {
7054 this.$floatableWindow
= $( this.getElementWindow() );
7055 this.$floatableWindow
.on( 'resize', this.onFloatableWindowResizeHandler
);
7057 if ( closestScrollableOfContainer
!== closestScrollableOfFloatable
) {
7058 this.$floatableClosestScrollable
= $( closestScrollableOfContainer
);
7059 this.$floatableClosestScrollable
.on( 'scroll', this.onFloatableScrollHandler
);
7062 // Initial position after visible
7065 if ( this.$floatableWindow
) {
7066 this.$floatableWindow
.off( 'resize', this.onFloatableWindowResizeHandler
);
7067 this.$floatableWindow
= null;
7070 if ( this.$floatableClosestScrollable
) {
7071 this.$floatableClosestScrollable
.off( 'scroll', this.onFloatableScrollHandler
);
7072 this.$floatableClosestScrollable
= null;
7075 this.$floatable
.css( { left
: '', top
: '' } );
7083 * Position the floatable below its container.
7085 * This should only be done when both of them are attached to the DOM and visible.
7089 OO
.ui
.mixin
.FloatableElement
.prototype.position = function () {
7092 if ( !this.positioning
) {
7096 pos
= OO
.ui
.Element
.static.getRelativePosition( this.$floatableContainer
, this.$floatable
.offsetParent() );
7098 // Position under container
7099 pos
.top
+= this.$floatableContainer
.height();
7100 this.$floatable
.css( pos
);
7102 // We updated the position, so re-evaluate the clipping state.
7103 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
7104 // will not notice the need to update itself.)
7105 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
7106 // it not listen to the right events in the right places?
7115 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
7116 * Accesskeys allow an user to go to a specific element by using
7117 * a shortcut combination of a browser specific keys + the key
7121 * // AccessKeyedElement provides an 'accesskey' attribute to the
7122 * // ButtonWidget class
7123 * var button = new OO.ui.ButtonWidget( {
7124 * label: 'Button with Accesskey',
7127 * $( 'body' ).append( button.$element );
7133 * @param {Object} [config] Configuration options
7134 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
7135 * If this config is omitted, the accesskey functionality is applied to $element, the
7136 * element created by the class.
7137 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
7138 * this config is omitted, no accesskey will be added.
7140 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
7141 // Configuration initialization
7142 config
= config
|| {};
7145 this.$accessKeyed
= null;
7146 this.accessKey
= null;
7149 this.setAccessKey( config
.accessKey
|| null );
7150 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
7155 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
7157 /* Static Properties */
7160 * The access key, a function that returns a key, or `null` for no accesskey.
7164 * @property {string|Function|null}
7166 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
7171 * Set the accesskeyed element.
7173 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
7174 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
7176 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
7178 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
7179 if ( this.$accessKeyed
) {
7180 this.$accessKeyed
.removeAttr( 'accesskey' );
7183 this.$accessKeyed
= $accessKeyed
;
7184 if ( this.accessKey
) {
7185 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
7192 * @param {string|Function|null} accesskey Key, a function that returns a key, or `null` for no accesskey
7195 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
7196 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
7198 if ( this.accessKey
!== accessKey
) {
7199 if ( this.$accessKeyed
) {
7200 if ( accessKey
!== null ) {
7201 this.$accessKeyed
.attr( 'accesskey', accessKey
);
7203 this.$accessKeyed
.removeAttr( 'accesskey' );
7206 this.accessKey
= accessKey
;
7215 * @return {string} accessKey string
7217 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
7218 return this.accessKey
;
7222 * Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute {@link OO.ui.Toolbar toolbars}.
7223 * Each tool is configured with a static name, title, and icon and is customized with the command to carry
7224 * out when the tool is selected. Tools must also be registered with a {@link OO.ui.ToolFactory tool factory},
7225 * which creates the tools on demand.
7227 * Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup},
7228 * {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which determine how
7229 * the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an example.
7231 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
7232 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7236 * @extends OO.ui.Widget
7237 * @mixins OO.ui.mixin.IconElement
7238 * @mixins OO.ui.mixin.FlaggedElement
7239 * @mixins OO.ui.mixin.TabIndexedElement
7242 * @param {OO.ui.ToolGroup} toolGroup
7243 * @param {Object} [config] Configuration options
7244 * @cfg {string|Function} [title] Title text or a function that returns text. If this config is omitted, the value of
7245 * the {@link #static-title static title} property is used.
7247 * The title is used in different ways depending on the type of toolgroup that contains the tool. The
7248 * 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
7249 * part of a {@link OO.ui.ListToolGroup list} or {@link OO.ui.MenuToolGroup menu} toolgroup.
7251 * For bar toolgroups, a description of the accelerator key is appended to the title if an accelerator key
7252 * is associated with an action by the same name as the tool and accelerator functionality has been added to the application.
7253 * To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method.
7255 OO
.ui
.Tool
= function OoUiTool( toolGroup
, config
) {
7256 // Allow passing positional parameters inside the config object
7257 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
7259 toolGroup
= config
.toolGroup
;
7262 // Configuration initialization
7263 config
= config
|| {};
7265 // Parent constructor
7266 OO
.ui
.Tool
.parent
.call( this, config
);
7269 this.toolGroup
= toolGroup
;
7270 this.toolbar
= this.toolGroup
.getToolbar();
7271 this.active
= false;
7272 this.$title
= $( '<span>' );
7273 this.$accel
= $( '<span>' );
7274 this.$link
= $( '<a>' );
7277 // Mixin constructors
7278 OO
.ui
.mixin
.IconElement
.call( this, config
);
7279 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
7280 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$link
} ) );
7283 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
7286 this.$title
.addClass( 'oo-ui-tool-title' );
7288 .addClass( 'oo-ui-tool-accel' )
7290 // This may need to be changed if the key names are ever localized,
7291 // but for now they are essentially written in English
7296 .addClass( 'oo-ui-tool-link' )
7297 .append( this.$icon
, this.$title
, this.$accel
)
7298 .attr( 'role', 'button' );
7300 .data( 'oo-ui-tool', this )
7302 'oo-ui-tool ' + 'oo-ui-tool-name-' +
7303 this.constructor.static.name
.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
7305 .toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel
)
7306 .append( this.$link
);
7307 this.setTitle( config
.title
|| this.constructor.static.title
);
7312 OO
.inheritClass( OO
.ui
.Tool
, OO
.ui
.Widget
);
7313 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.IconElement
);
7314 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.FlaggedElement
);
7315 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.TabIndexedElement
);
7317 /* Static Properties */
7323 OO
.ui
.Tool
.static.tagName
= 'span';
7326 * Symbolic name of tool.
7328 * The symbolic name is used internally to register the tool with a {@link OO.ui.ToolFactory ToolFactory}. It can
7329 * also be used when adding tools to toolgroups.
7334 * @property {string}
7336 OO
.ui
.Tool
.static.name
= '';
7339 * Symbolic name of the group.
7341 * The group name is used to associate tools with each other so that they can be selected later by
7342 * a {@link OO.ui.ToolGroup toolgroup}.
7347 * @property {string}
7349 OO
.ui
.Tool
.static.group
= '';
7352 * 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.
7357 * @property {string|Function}
7359 OO
.ui
.Tool
.static.title
= '';
7362 * Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup.
7363 * Normally only the icon is displayed, or only the label if no icon is given.
7367 * @property {boolean}
7369 OO
.ui
.Tool
.static.displayBothIconAndLabel
= false;
7372 * Add tool to catch-all groups automatically.
7374 * A catch-all group, which contains all tools that do not currently belong to a toolgroup,
7375 * can be included in a toolgroup using the wildcard selector, an asterisk (*).
7379 * @property {boolean}
7381 OO
.ui
.Tool
.static.autoAddToCatchall
= true;
7384 * Add tool to named groups automatically.
7386 * By default, tools that are configured with a static ‘group’ property are added
7387 * to that group and will be selected when the symbolic name of the group is specified (e.g., when
7388 * toolgroups include tools by group name).
7391 * @property {boolean}
7394 OO
.ui
.Tool
.static.autoAddToGroup
= true;
7397 * Check if this tool is compatible with given data.
7399 * This is a stub that can be overriden to provide support for filtering tools based on an
7400 * arbitrary piece of information (e.g., where the cursor is in a document). The implementation
7401 * must also call this method so that the compatibility check can be performed.
7405 * @param {Mixed} data Data to check
7406 * @return {boolean} Tool can be used with data
7408 OO
.ui
.Tool
.static.isCompatibleWith = function () {
7415 * Handle the toolbar state being updated.
7417 * This is an abstract method that must be overridden in a concrete subclass.
7423 OO
.ui
.Tool
.prototype.onUpdateState
= null;
7426 * Handle the tool being selected.
7428 * This is an abstract method that must be overridden in a concrete subclass.
7434 OO
.ui
.Tool
.prototype.onSelect
= null;
7437 * Check if the tool is active.
7439 * Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed
7440 * with the #setActive method. Additional CSS is applied to the tool to reflect the active state.
7442 * @return {boolean} Tool is active
7444 OO
.ui
.Tool
.prototype.isActive = function () {
7449 * Make the tool appear active or inactive.
7451 * This method should be called within #onSelect or #onUpdateState event handlers to make the tool
7452 * appear pressed or not.
7454 * @param {boolean} state Make tool appear active
7456 OO
.ui
.Tool
.prototype.setActive = function ( state
) {
7457 this.active
= !!state
;
7458 if ( this.active
) {
7459 this.$element
.addClass( 'oo-ui-tool-active' );
7461 this.$element
.removeClass( 'oo-ui-tool-active' );
7466 * Set the tool #title.
7468 * @param {string|Function} title Title text or a function that returns text
7471 OO
.ui
.Tool
.prototype.setTitle = function ( title
) {
7472 this.title
= OO
.ui
.resolveMsg( title
);
7478 * Get the tool #title.
7480 * @return {string} Title text
7482 OO
.ui
.Tool
.prototype.getTitle = function () {
7487 * Get the tool's symbolic name.
7489 * @return {string} Symbolic name of tool
7491 OO
.ui
.Tool
.prototype.getName = function () {
7492 return this.constructor.static.name
;
7498 OO
.ui
.Tool
.prototype.updateTitle = function () {
7499 var titleTooltips
= this.toolGroup
.constructor.static.titleTooltips
,
7500 accelTooltips
= this.toolGroup
.constructor.static.accelTooltips
,
7501 accel
= this.toolbar
.getToolAccelerator( this.constructor.static.name
),
7504 this.$title
.text( this.title
);
7505 this.$accel
.text( accel
);
7507 if ( titleTooltips
&& typeof this.title
=== 'string' && this.title
.length
) {
7508 tooltipParts
.push( this.title
);
7510 if ( accelTooltips
&& typeof accel
=== 'string' && accel
.length
) {
7511 tooltipParts
.push( accel
);
7513 if ( tooltipParts
.length
) {
7514 this.$link
.attr( 'title', tooltipParts
.join( ' ' ) );
7516 this.$link
.removeAttr( 'title' );
7523 * Destroying the tool removes all event handlers and the tool’s DOM elements.
7524 * Call this method whenever you are done using a tool.
7526 OO
.ui
.Tool
.prototype.destroy = function () {
7527 this.toolbar
.disconnect( this );
7528 this.$element
.remove();
7532 * Toolbars are complex interface components that permit users to easily access a variety
7533 * of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional commands that are
7534 * part of the toolbar, but not configured as tools.
7536 * Individual tools are customized and then registered with a {@link OO.ui.ToolFactory tool factory}, which creates
7537 * the tools on demand. Each tool has a symbolic name (used when registering the tool), a title (e.g., ‘Insert
7538 * image’), and an icon.
7540 * Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be {@link OO.ui.MenuToolGroup menus}
7541 * of tools, {@link OO.ui.ListToolGroup lists} of tools, or a single {@link OO.ui.BarToolGroup bar} of tools.
7542 * The arrangement and order of the toolgroups is customized when the toolbar is set up. Tools can be presented in
7543 * any order, but each can only appear once in the toolbar.
7545 * The following is an example of a basic toolbar.
7548 * // Example of a toolbar
7549 * // Create the toolbar
7550 * var toolFactory = new OO.ui.ToolFactory();
7551 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7552 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7554 * // We will be placing status text in this element when tools are used
7555 * var $area = $( '<p>' ).text( 'Toolbar example' );
7557 * // Define the tools that we're going to place in our toolbar
7559 * // Create a class inheriting from OO.ui.Tool
7560 * function ImageTool() {
7561 * ImageTool.parent.apply( this, arguments );
7563 * OO.inheritClass( ImageTool, OO.ui.Tool );
7564 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7565 * // of 'icon' and 'title' (displayed icon and text).
7566 * ImageTool.static.name = 'image';
7567 * ImageTool.static.icon = 'image';
7568 * ImageTool.static.title = 'Insert image';
7569 * // Defines the action that will happen when this tool is selected (clicked).
7570 * ImageTool.prototype.onSelect = function () {
7571 * $area.text( 'Image tool clicked!' );
7572 * // Never display this tool as "active" (selected).
7573 * this.setActive( false );
7575 * // Make this tool available in our toolFactory and thus our toolbar
7576 * toolFactory.register( ImageTool );
7578 * // Register two more tools, nothing interesting here
7579 * function SettingsTool() {
7580 * SettingsTool.parent.apply( this, arguments );
7582 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7583 * SettingsTool.static.name = 'settings';
7584 * SettingsTool.static.icon = 'settings';
7585 * SettingsTool.static.title = 'Change settings';
7586 * SettingsTool.prototype.onSelect = function () {
7587 * $area.text( 'Settings tool clicked!' );
7588 * this.setActive( false );
7590 * toolFactory.register( SettingsTool );
7592 * // Register two more tools, nothing interesting here
7593 * function StuffTool() {
7594 * StuffTool.parent.apply( this, arguments );
7596 * OO.inheritClass( StuffTool, OO.ui.Tool );
7597 * StuffTool.static.name = 'stuff';
7598 * StuffTool.static.icon = 'ellipsis';
7599 * StuffTool.static.title = 'More stuff';
7600 * StuffTool.prototype.onSelect = function () {
7601 * $area.text( 'More stuff tool clicked!' );
7602 * this.setActive( false );
7604 * toolFactory.register( StuffTool );
7606 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7607 * // little popup window (a PopupWidget).
7608 * function HelpTool( toolGroup, config ) {
7609 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7614 * this.popup.$body.append( '<p>I am helpful!</p>' );
7616 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7617 * HelpTool.static.name = 'help';
7618 * HelpTool.static.icon = 'help';
7619 * HelpTool.static.title = 'Help';
7620 * toolFactory.register( HelpTool );
7622 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7623 * // used once (but not all defined tools must be used).
7626 * // 'bar' tool groups display tools' icons only, side-by-side.
7628 * include: [ 'image', 'help' ]
7631 * // 'list' tool groups display both the titles and icons, in a dropdown list.
7633 * indicator: 'down',
7635 * include: [ 'settings', 'stuff' ]
7637 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
7638 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here,
7639 * // since it's more complicated to use. (See the next example snippet on this page.)
7642 * // Create some UI around the toolbar and place it in the document
7643 * var frame = new OO.ui.PanelLayout( {
7647 * var contentFrame = new OO.ui.PanelLayout( {
7651 * frame.$element.append(
7653 * contentFrame.$element.append( $area )
7655 * $( 'body' ).append( frame.$element );
7657 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7659 * toolbar.initialize();
7661 * The following example extends the previous one to illustrate 'menu' toolgroups and the usage of
7662 * 'updateState' event.
7665 * // Create the toolbar
7666 * var toolFactory = new OO.ui.ToolFactory();
7667 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7668 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7670 * // We will be placing status text in this element when tools are used
7671 * var $area = $( '<p>' ).text( 'Toolbar example' );
7673 * // Define the tools that we're going to place in our toolbar
7675 * // Create a class inheriting from OO.ui.Tool
7676 * function ImageTool() {
7677 * ImageTool.parent.apply( this, arguments );
7679 * OO.inheritClass( ImageTool, OO.ui.Tool );
7680 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7681 * // of 'icon' and 'title' (displayed icon and text).
7682 * ImageTool.static.name = 'image';
7683 * ImageTool.static.icon = 'image';
7684 * ImageTool.static.title = 'Insert image';
7685 * // Defines the action that will happen when this tool is selected (clicked).
7686 * ImageTool.prototype.onSelect = function () {
7687 * $area.text( 'Image tool clicked!' );
7688 * // Never display this tool as "active" (selected).
7689 * this.setActive( false );
7691 * // The toolbar can be synchronized with the state of some external stuff, like a text
7692 * // editor's editing area, highlighting the tools (e.g. a 'bold' tool would be shown as active
7693 * // when the text cursor was inside bolded text). Here we simply disable this feature.
7694 * ImageTool.prototype.onUpdateState = function () {
7696 * // Make this tool available in our toolFactory and thus our toolbar
7697 * toolFactory.register( ImageTool );
7699 * // Register two more tools, nothing interesting here
7700 * function SettingsTool() {
7701 * SettingsTool.parent.apply( this, arguments );
7702 * this.reallyActive = false;
7704 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7705 * SettingsTool.static.name = 'settings';
7706 * SettingsTool.static.icon = 'settings';
7707 * SettingsTool.static.title = 'Change settings';
7708 * SettingsTool.prototype.onSelect = function () {
7709 * $area.text( 'Settings tool clicked!' );
7710 * // Toggle the active state on each click
7711 * this.reallyActive = !this.reallyActive;
7712 * this.setActive( this.reallyActive );
7713 * // To update the menu label
7714 * this.toolbar.emit( 'updateState' );
7716 * SettingsTool.prototype.onUpdateState = function () {
7718 * toolFactory.register( SettingsTool );
7720 * // Register two more tools, nothing interesting here
7721 * function StuffTool() {
7722 * StuffTool.parent.apply( this, arguments );
7723 * this.reallyActive = false;
7725 * OO.inheritClass( StuffTool, OO.ui.Tool );
7726 * StuffTool.static.name = 'stuff';
7727 * StuffTool.static.icon = 'ellipsis';
7728 * StuffTool.static.title = 'More stuff';
7729 * StuffTool.prototype.onSelect = function () {
7730 * $area.text( 'More stuff tool clicked!' );
7731 * // Toggle the active state on each click
7732 * this.reallyActive = !this.reallyActive;
7733 * this.setActive( this.reallyActive );
7734 * // To update the menu label
7735 * this.toolbar.emit( 'updateState' );
7737 * StuffTool.prototype.onUpdateState = function () {
7739 * toolFactory.register( StuffTool );
7741 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7742 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
7743 * function HelpTool( toolGroup, config ) {
7744 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7749 * this.popup.$body.append( '<p>I am helpful!</p>' );
7751 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7752 * HelpTool.static.name = 'help';
7753 * HelpTool.static.icon = 'help';
7754 * HelpTool.static.title = 'Help';
7755 * toolFactory.register( HelpTool );
7757 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7758 * // used once (but not all defined tools must be used).
7761 * // 'bar' tool groups display tools' icons only, side-by-side.
7763 * include: [ 'image', 'help' ]
7766 * // 'menu' tool groups display both the titles and icons, in a dropdown menu.
7767 * // Menu label indicates which items are selected.
7769 * indicator: 'down',
7770 * include: [ 'settings', 'stuff' ]
7774 * // Create some UI around the toolbar and place it in the document
7775 * var frame = new OO.ui.PanelLayout( {
7779 * var contentFrame = new OO.ui.PanelLayout( {
7783 * frame.$element.append(
7785 * contentFrame.$element.append( $area )
7787 * $( 'body' ).append( frame.$element );
7789 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7791 * toolbar.initialize();
7792 * toolbar.emit( 'updateState' );
7795 * @extends OO.ui.Element
7796 * @mixins OO.EventEmitter
7797 * @mixins OO.ui.mixin.GroupElement
7800 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
7801 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups
7802 * @param {Object} [config] Configuration options
7803 * @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are included
7804 * in the toolbar, but are not configured as tools. By default, actions are displayed on the right side of
7806 * @cfg {boolean} [shadow] Add a shadow below the toolbar.
7808 OO
.ui
.Toolbar
= function OoUiToolbar( toolFactory
, toolGroupFactory
, config
) {
7809 // Allow passing positional parameters inside the config object
7810 if ( OO
.isPlainObject( toolFactory
) && config
=== undefined ) {
7811 config
= toolFactory
;
7812 toolFactory
= config
.toolFactory
;
7813 toolGroupFactory
= config
.toolGroupFactory
;
7816 // Configuration initialization
7817 config
= config
|| {};
7819 // Parent constructor
7820 OO
.ui
.Toolbar
.parent
.call( this, config
);
7822 // Mixin constructors
7823 OO
.EventEmitter
.call( this );
7824 OO
.ui
.mixin
.GroupElement
.call( this, config
);
7827 this.toolFactory
= toolFactory
;
7828 this.toolGroupFactory
= toolGroupFactory
;
7831 this.$bar
= $( '<div>' );
7832 this.$actions
= $( '<div>' );
7833 this.initialized
= false;
7834 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
7838 .add( this.$bar
).add( this.$group
).add( this.$actions
)
7839 .on( 'mousedown keydown', this.onPointerDown
.bind( this ) );
7842 this.$group
.addClass( 'oo-ui-toolbar-tools' );
7843 if ( config
.actions
) {
7844 this.$bar
.append( this.$actions
.addClass( 'oo-ui-toolbar-actions' ) );
7847 .addClass( 'oo-ui-toolbar-bar' )
7848 .append( this.$group
, '<div style="clear:both"></div>' );
7849 if ( config
.shadow
) {
7850 this.$bar
.append( '<div class="oo-ui-toolbar-shadow"></div>' );
7852 this.$element
.addClass( 'oo-ui-toolbar' ).append( this.$bar
);
7857 OO
.inheritClass( OO
.ui
.Toolbar
, OO
.ui
.Element
);
7858 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.EventEmitter
);
7859 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.ui
.mixin
.GroupElement
);
7864 * Get the tool factory.
7866 * @return {OO.ui.ToolFactory} Tool factory
7868 OO
.ui
.Toolbar
.prototype.getToolFactory = function () {
7869 return this.toolFactory
;
7873 * Get the toolgroup factory.
7875 * @return {OO.Factory} Toolgroup factory
7877 OO
.ui
.Toolbar
.prototype.getToolGroupFactory = function () {
7878 return this.toolGroupFactory
;
7882 * Handles mouse down events.
7885 * @param {jQuery.Event} e Mouse down event
7887 OO
.ui
.Toolbar
.prototype.onPointerDown = function ( e
) {
7888 var $closestWidgetToEvent
= $( e
.target
).closest( '.oo-ui-widget' ),
7889 $closestWidgetToToolbar
= this.$element
.closest( '.oo-ui-widget' );
7890 if ( !$closestWidgetToEvent
.length
|| $closestWidgetToEvent
[ 0 ] === $closestWidgetToToolbar
[ 0 ] ) {
7896 * Handle window resize event.
7899 * @param {jQuery.Event} e Window resize event
7901 OO
.ui
.Toolbar
.prototype.onWindowResize = function () {
7902 this.$element
.toggleClass(
7903 'oo-ui-toolbar-narrow',
7904 this.$bar
.width() <= this.narrowThreshold
7909 * Sets up handles and preloads required information for the toolbar to work.
7910 * This must be called after it is attached to a visible document and before doing anything else.
7912 OO
.ui
.Toolbar
.prototype.initialize = function () {
7913 if ( !this.initialized
) {
7914 this.initialized
= true;
7915 this.narrowThreshold
= this.$group
.width() + this.$actions
.width();
7916 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
7917 this.onWindowResize();
7922 * Set up the toolbar.
7924 * The toolbar is set up with a list of toolgroup configurations that specify the type of
7925 * toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or {@link OO.ui.ListToolGroup list})
7926 * to add and which tools to include, exclude, promote, or demote within that toolgroup. Please
7927 * see {@link OO.ui.ToolGroup toolgroups} for more information about including tools in toolgroups.
7929 * @param {Object.<string,Array>} groups List of toolgroup configurations
7930 * @param {Array|string} [groups.include] Tools to include in the toolgroup
7931 * @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup
7932 * @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup
7933 * @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup
7935 OO
.ui
.Toolbar
.prototype.setup = function ( groups
) {
7936 var i
, len
, type
, group
,
7938 defaultType
= 'bar';
7940 // Cleanup previous groups
7943 // Build out new groups
7944 for ( i
= 0, len
= groups
.length
; i
< len
; i
++ ) {
7945 group
= groups
[ i
];
7946 if ( group
.include
=== '*' ) {
7947 // Apply defaults to catch-all groups
7948 if ( group
.type
=== undefined ) {
7949 group
.type
= 'list';
7951 if ( group
.label
=== undefined ) {
7952 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
7955 // Check type has been registered
7956 type
= this.getToolGroupFactory().lookup( group
.type
) ? group
.type
: defaultType
;
7958 this.getToolGroupFactory().create( type
, this, group
)
7961 this.addItems( items
);
7965 * Remove all tools and toolgroups from the toolbar.
7967 OO
.ui
.Toolbar
.prototype.reset = function () {
7972 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
7973 this.items
[ i
].destroy();
7979 * Destroy the toolbar.
7981 * Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. Call
7982 * this method whenever you are done using a toolbar.
7984 OO
.ui
.Toolbar
.prototype.destroy = function () {
7985 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
7987 this.$element
.remove();
7991 * Check if the tool is available.
7993 * Available tools are ones that have not yet been added to the toolbar.
7995 * @param {string} name Symbolic name of tool
7996 * @return {boolean} Tool is available
7998 OO
.ui
.Toolbar
.prototype.isToolAvailable = function ( name
) {
7999 return !this.tools
[ name
];
8003 * Prevent tool from being used again.
8005 * @param {OO.ui.Tool} tool Tool to reserve
8007 OO
.ui
.Toolbar
.prototype.reserveTool = function ( tool
) {
8008 this.tools
[ tool
.getName() ] = tool
;
8012 * Allow tool to be used again.
8014 * @param {OO.ui.Tool} tool Tool to release
8016 OO
.ui
.Toolbar
.prototype.releaseTool = function ( tool
) {
8017 delete this.tools
[ tool
.getName() ];
8021 * Get accelerator label for tool.
8023 * The OOjs UI library does not contain an accelerator system, but this is the hook for one. To
8024 * use an accelerator system, subclass the toolbar and override this method, which is meant to return a label
8025 * that describes the accelerator keys for the tool passed (by symbolic name) to the method.
8027 * @param {string} name Symbolic name of tool
8028 * @return {string|undefined} Tool accelerator label if available
8030 OO
.ui
.Toolbar
.prototype.getToolAccelerator = function () {
8035 * ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a {@link OO.ui.Toolbar toolbar}.
8036 * The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or {@link OO.ui.MenuToolGroup menu})
8037 * to which a tool belongs determines how the tool is arranged and displayed in the toolbar. Toolgroups
8038 * themselves are created on demand with a {@link OO.ui.ToolGroupFactory toolgroup factory}.
8040 * Toolgroups can contain individual tools, groups of tools, or all available tools:
8042 * To include an individual tool (or array of individual tools), specify tools by symbolic name:
8044 * include: [ 'tool-name' ] or [ { name: 'tool-name' }]
8046 * 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.)
8048 * include: [ { group: 'group-name' } ]
8050 * To include all tools that are not yet assigned to a toolgroup, use the catch-all selector, an asterisk (*):
8054 * See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in general,
8055 * please see the [OOjs UI documentation on MediaWiki][1].
8057 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
8061 * @extends OO.ui.Widget
8062 * @mixins OO.ui.mixin.GroupElement
8065 * @param {OO.ui.Toolbar} toolbar
8066 * @param {Object} [config] Configuration options
8067 * @cfg {Array|string} [include=[]] List of tools to include in the toolgroup.
8068 * @cfg {Array|string} [exclude=[]] List of tools to exclude from the toolgroup.
8069 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning of the toolgroup.
8070 * @cfg {Array|string} [demote=[]] List of tools to demote to the end of the toolgroup.
8071 * This setting is particularly useful when tools have been added to the toolgroup
8072 * en masse (e.g., via the catch-all selector).
8074 OO
.ui
.ToolGroup
= function OoUiToolGroup( toolbar
, config
) {
8075 // Allow passing positional parameters inside the config object
8076 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
8078 toolbar
= config
.toolbar
;
8081 // Configuration initialization
8082 config
= config
|| {};
8084 // Parent constructor
8085 OO
.ui
.ToolGroup
.parent
.call( this, config
);
8087 // Mixin constructors
8088 OO
.ui
.mixin
.GroupElement
.call( this, config
);
8091 this.toolbar
= toolbar
;
8093 this.pressed
= null;
8094 this.autoDisabled
= false;
8095 this.include
= config
.include
|| [];
8096 this.exclude
= config
.exclude
|| [];
8097 this.promote
= config
.promote
|| [];
8098 this.demote
= config
.demote
|| [];
8099 this.onCapturedMouseKeyUpHandler
= this.onCapturedMouseKeyUp
.bind( this );
8103 mousedown
: this.onMouseKeyDown
.bind( this ),
8104 mouseup
: this.onMouseKeyUp
.bind( this ),
8105 keydown
: this.onMouseKeyDown
.bind( this ),
8106 keyup
: this.onMouseKeyUp
.bind( this ),
8107 focus
: this.onMouseOverFocus
.bind( this ),
8108 blur
: this.onMouseOutBlur
.bind( this ),
8109 mouseover
: this.onMouseOverFocus
.bind( this ),
8110 mouseout
: this.onMouseOutBlur
.bind( this )
8112 this.toolbar
.getToolFactory().connect( this, { register
: 'onToolFactoryRegister' } );
8113 this.aggregate( { disable
: 'itemDisable' } );
8114 this.connect( this, { itemDisable
: 'updateDisabled' } );
8117 this.$group
.addClass( 'oo-ui-toolGroup-tools' );
8119 .addClass( 'oo-ui-toolGroup' )
8120 .append( this.$group
);
8126 OO
.inheritClass( OO
.ui
.ToolGroup
, OO
.ui
.Widget
);
8127 OO
.mixinClass( OO
.ui
.ToolGroup
, OO
.ui
.mixin
.GroupElement
);
8135 /* Static Properties */
8138 * Show labels in tooltips.
8142 * @property {boolean}
8144 OO
.ui
.ToolGroup
.static.titleTooltips
= false;
8147 * Show acceleration labels in tooltips.
8149 * Note: The OOjs UI library does not include an accelerator system, but does contain
8150 * a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and
8151 * override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is
8152 * meant to return a label that describes the accelerator keys for a given tool (e.g., 'Ctrl + M').
8156 * @property {boolean}
8158 OO
.ui
.ToolGroup
.static.accelTooltips
= false;
8161 * Automatically disable the toolgroup when all tools are disabled
8165 * @property {boolean}
8167 OO
.ui
.ToolGroup
.static.autoDisable
= true;
8174 OO
.ui
.ToolGroup
.prototype.isDisabled = function () {
8175 return this.autoDisabled
|| OO
.ui
.ToolGroup
.parent
.prototype.isDisabled
.apply( this, arguments
);
8181 OO
.ui
.ToolGroup
.prototype.updateDisabled = function () {
8182 var i
, item
, allDisabled
= true;
8184 if ( this.constructor.static.autoDisable
) {
8185 for ( i
= this.items
.length
- 1; i
>= 0; i
-- ) {
8186 item
= this.items
[ i
];
8187 if ( !item
.isDisabled() ) {
8188 allDisabled
= false;
8192 this.autoDisabled
= allDisabled
;
8194 OO
.ui
.ToolGroup
.parent
.prototype.updateDisabled
.apply( this, arguments
);
8198 * Handle mouse down and key down events.
8201 * @param {jQuery.Event} e Mouse down or key down event
8203 OO
.ui
.ToolGroup
.prototype.onMouseKeyDown = function ( e
) {
8205 !this.isDisabled() &&
8206 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
8208 this.pressed
= this.getTargetTool( e
);
8209 if ( this.pressed
) {
8210 this.pressed
.setActive( true );
8211 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler
);
8212 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler
);
8219 * Handle captured mouse up and key up events.
8222 * @param {Event} e Mouse up or key up event
8224 OO
.ui
.ToolGroup
.prototype.onCapturedMouseKeyUp = function ( e
) {
8225 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler
);
8226 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler
);
8227 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
8228 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
8229 this.onMouseKeyUp( e
);
8233 * Handle mouse up and key up events.
8236 * @param {jQuery.Event} e Mouse up or key up event
8238 OO
.ui
.ToolGroup
.prototype.onMouseKeyUp = function ( e
) {
8239 var tool
= this.getTargetTool( e
);
8242 !this.isDisabled() && this.pressed
&& this.pressed
=== tool
&&
8243 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
8245 this.pressed
.onSelect();
8246 this.pressed
= null;
8250 this.pressed
= null;
8254 * Handle mouse over and focus events.
8257 * @param {jQuery.Event} e Mouse over or focus event
8259 OO
.ui
.ToolGroup
.prototype.onMouseOverFocus = function ( e
) {
8260 var tool
= this.getTargetTool( e
);
8262 if ( this.pressed
&& this.pressed
=== tool
) {
8263 this.pressed
.setActive( true );
8268 * Handle mouse out and blur events.
8271 * @param {jQuery.Event} e Mouse out or blur event
8273 OO
.ui
.ToolGroup
.prototype.onMouseOutBlur = function ( e
) {
8274 var tool
= this.getTargetTool( e
);
8276 if ( this.pressed
&& this.pressed
=== tool
) {
8277 this.pressed
.setActive( false );
8282 * Get the closest tool to a jQuery.Event.
8284 * Only tool links are considered, which prevents other elements in the tool such as popups from
8285 * triggering tool group interactions.
8288 * @param {jQuery.Event} e
8289 * @return {OO.ui.Tool|null} Tool, `null` if none was found
8291 OO
.ui
.ToolGroup
.prototype.getTargetTool = function ( e
) {
8293 $item
= $( e
.target
).closest( '.oo-ui-tool-link' );
8295 if ( $item
.length
) {
8296 tool
= $item
.parent().data( 'oo-ui-tool' );
8299 return tool
&& !tool
.isDisabled() ? tool
: null;
8303 * Handle tool registry register events.
8305 * If a tool is registered after the group is created, we must repopulate the list to account for:
8307 * - a tool being added that may be included
8308 * - a tool already included being overridden
8311 * @param {string} name Symbolic name of tool
8313 OO
.ui
.ToolGroup
.prototype.onToolFactoryRegister = function () {
8318 * Get the toolbar that contains the toolgroup.
8320 * @return {OO.ui.Toolbar} Toolbar that contains the toolgroup
8322 OO
.ui
.ToolGroup
.prototype.getToolbar = function () {
8323 return this.toolbar
;
8327 * Add and remove tools based on configuration.
8329 OO
.ui
.ToolGroup
.prototype.populate = function () {
8330 var i
, len
, name
, tool
,
8331 toolFactory
= this.toolbar
.getToolFactory(),
8335 list
= this.toolbar
.getToolFactory().getTools(
8336 this.include
, this.exclude
, this.promote
, this.demote
8339 // Build a list of needed tools
8340 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
8344 toolFactory
.lookup( name
) &&
8345 // Tool is available or is already in this group
8346 ( this.toolbar
.isToolAvailable( name
) || this.tools
[ name
] )
8348 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
8349 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
8350 this.toolbar
.tools
[ name
] = true;
8351 tool
= this.tools
[ name
];
8353 // Auto-initialize tools on first use
8354 this.tools
[ name
] = tool
= toolFactory
.create( name
, this );
8357 this.toolbar
.reserveTool( tool
);
8359 names
[ name
] = true;
8362 // Remove tools that are no longer needed
8363 for ( name
in this.tools
) {
8364 if ( !names
[ name
] ) {
8365 this.tools
[ name
].destroy();
8366 this.toolbar
.releaseTool( this.tools
[ name
] );
8367 remove
.push( this.tools
[ name
] );
8368 delete this.tools
[ name
];
8371 if ( remove
.length
) {
8372 this.removeItems( remove
);
8374 // Update emptiness state
8376 this.$element
.removeClass( 'oo-ui-toolGroup-empty' );
8378 this.$element
.addClass( 'oo-ui-toolGroup-empty' );
8380 // Re-add tools (moving existing ones to new locations)
8381 this.addItems( add
);
8382 // Disabled state may depend on items
8383 this.updateDisabled();
8387 * Destroy toolgroup.
8389 OO
.ui
.ToolGroup
.prototype.destroy = function () {
8393 this.toolbar
.getToolFactory().disconnect( this );
8394 for ( name
in this.tools
) {
8395 this.toolbar
.releaseTool( this.tools
[ name
] );
8396 this.tools
[ name
].disconnect( this ).destroy();
8397 delete this.tools
[ name
];
8399 this.$element
.remove();
8403 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
8404 * consists of a header that contains the dialog title, a body with the message, and a footer that
8405 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
8406 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
8408 * There are two basic types of message dialogs, confirmation and alert:
8410 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
8411 * more details about the consequences.
8412 * - **alert**: the dialog title describes which event occurred and the message provides more information
8413 * about why the event occurred.
8415 * The MessageDialog class specifies two actions: ‘accept’, the primary
8416 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
8417 * passing along the selected action.
8419 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
8422 * // Example: Creating and opening a message dialog window.
8423 * var messageDialog = new OO.ui.MessageDialog();
8425 * // Create and append a window manager.
8426 * var windowManager = new OO.ui.WindowManager();
8427 * $( 'body' ).append( windowManager.$element );
8428 * windowManager.addWindows( [ messageDialog ] );
8429 * // Open the window.
8430 * windowManager.openWindow( messageDialog, {
8431 * title: 'Basic message dialog',
8432 * message: 'This is the message'
8435 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
8438 * @extends OO.ui.Dialog
8441 * @param {Object} [config] Configuration options
8443 OO
.ui
.MessageDialog
= function OoUiMessageDialog( config
) {
8444 // Parent constructor
8445 OO
.ui
.MessageDialog
.parent
.call( this, config
);
8448 this.verticalActionLayout
= null;
8451 this.$element
.addClass( 'oo-ui-messageDialog' );
8456 OO
.inheritClass( OO
.ui
.MessageDialog
, OO
.ui
.Dialog
);
8458 /* Static Properties */
8460 OO
.ui
.MessageDialog
.static.name
= 'message';
8462 OO
.ui
.MessageDialog
.static.size
= 'small';
8464 OO
.ui
.MessageDialog
.static.verbose
= false;
8469 * The title of a confirmation dialog describes what a progressive action will do. The
8470 * title of an alert dialog describes which event occurred.
8474 * @property {jQuery|string|Function|null}
8476 OO
.ui
.MessageDialog
.static.title
= null;
8479 * The message displayed in the dialog body.
8481 * A confirmation message describes the consequences of a progressive action. An alert
8482 * message describes why an event occurred.
8486 * @property {jQuery|string|Function|null}
8488 OO
.ui
.MessageDialog
.static.message
= null;
8490 OO
.ui
.MessageDialog
.static.actions
= [
8491 { action
: 'accept', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-accept' ), flags
: 'primary' },
8492 { action
: 'reject', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-reject' ), flags
: 'safe' }
8500 OO
.ui
.MessageDialog
.prototype.setManager = function ( manager
) {
8501 OO
.ui
.MessageDialog
.parent
.prototype.setManager
.call( this, manager
);
8504 this.manager
.connect( this, {
8514 OO
.ui
.MessageDialog
.prototype.onActionResize = function ( action
) {
8516 return OO
.ui
.MessageDialog
.parent
.prototype.onActionResize
.call( this, action
);
8520 * Handle window resized events.
8524 OO
.ui
.MessageDialog
.prototype.onResize = function () {
8526 dialog
.fitActions();
8527 // Wait for CSS transition to finish and do it again :(
8528 setTimeout( function () {
8529 dialog
.fitActions();
8534 * Toggle action layout between vertical and horizontal.
8537 * @param {boolean} [value] Layout actions vertically, omit to toggle
8540 OO
.ui
.MessageDialog
.prototype.toggleVerticalActionLayout = function ( value
) {
8541 value
= value
=== undefined ? !this.verticalActionLayout
: !!value
;
8543 if ( value
!== this.verticalActionLayout
) {
8544 this.verticalActionLayout
= value
;
8546 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value
)
8547 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value
);
8556 OO
.ui
.MessageDialog
.prototype.getActionProcess = function ( action
) {
8558 return new OO
.ui
.Process( function () {
8559 this.close( { action
: action
} );
8562 return OO
.ui
.MessageDialog
.parent
.prototype.getActionProcess
.call( this, action
);
8568 * @param {Object} [data] Dialog opening data
8569 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
8570 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
8571 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
8572 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
8575 OO
.ui
.MessageDialog
.prototype.getSetupProcess = function ( data
) {
8579 return OO
.ui
.MessageDialog
.parent
.prototype.getSetupProcess
.call( this, data
)
8580 .next( function () {
8581 this.title
.setLabel(
8582 data
.title
!== undefined ? data
.title
: this.constructor.static.title
8584 this.message
.setLabel(
8585 data
.message
!== undefined ? data
.message
: this.constructor.static.message
8587 this.message
.$element
.toggleClass(
8588 'oo-ui-messageDialog-message-verbose',
8589 data
.verbose
!== undefined ? data
.verbose
: this.constructor.static.verbose
8597 OO
.ui
.MessageDialog
.prototype.getReadyProcess = function ( data
) {
8601 return OO
.ui
.MessageDialog
.parent
.prototype.getReadyProcess
.call( this, data
)
8602 .next( function () {
8603 // Focus the primary action button
8604 var actions
= this.actions
.get();
8605 actions
= actions
.filter( function ( action
) {
8606 return action
.getFlags().indexOf( 'primary' ) > -1;
8608 if ( actions
.length
> 0 ) {
8609 actions
[ 0 ].$button
.focus();
8617 OO
.ui
.MessageDialog
.prototype.getBodyHeight = function () {
8618 var bodyHeight
, oldOverflow
,
8619 $scrollable
= this.container
.$element
;
8621 oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
8622 $scrollable
[ 0 ].style
.overflow
= 'hidden';
8624 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
8626 bodyHeight
= this.text
.$element
.outerHeight( true );
8627 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
8635 OO
.ui
.MessageDialog
.prototype.setDimensions = function ( dim
) {
8636 var $scrollable
= this.container
.$element
;
8637 OO
.ui
.MessageDialog
.parent
.prototype.setDimensions
.call( this, dim
);
8639 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
8640 // Need to do it after transition completes (250ms), add 50ms just in case.
8641 setTimeout( function () {
8642 var oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
8643 $scrollable
[ 0 ].style
.overflow
= 'hidden';
8645 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
8647 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
8656 OO
.ui
.MessageDialog
.prototype.initialize = function () {
8658 OO
.ui
.MessageDialog
.parent
.prototype.initialize
.call( this );
8661 this.$actions
= $( '<div>' );
8662 this.container
= new OO
.ui
.PanelLayout( {
8663 scrollable
: true, classes
: [ 'oo-ui-messageDialog-container' ]
8665 this.text
= new OO
.ui
.PanelLayout( {
8666 padded
: true, expanded
: false, classes
: [ 'oo-ui-messageDialog-text' ]
8668 this.message
= new OO
.ui
.LabelWidget( {
8669 classes
: [ 'oo-ui-messageDialog-message' ]
8673 this.title
.$element
.addClass( 'oo-ui-messageDialog-title' );
8674 this.$content
.addClass( 'oo-ui-messageDialog-content' );
8675 this.container
.$element
.append( this.text
.$element
);
8676 this.text
.$element
.append( this.title
.$element
, this.message
.$element
);
8677 this.$body
.append( this.container
.$element
);
8678 this.$actions
.addClass( 'oo-ui-messageDialog-actions' );
8679 this.$foot
.append( this.$actions
);
8685 OO
.ui
.MessageDialog
.prototype.attachActions = function () {
8686 var i
, len
, other
, special
, others
;
8689 OO
.ui
.MessageDialog
.parent
.prototype.attachActions
.call( this );
8691 special
= this.actions
.getSpecial();
8692 others
= this.actions
.getOthers();
8694 if ( special
.safe
) {
8695 this.$actions
.append( special
.safe
.$element
);
8696 special
.safe
.toggleFramed( false );
8698 if ( others
.length
) {
8699 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
8700 other
= others
[ i
];
8701 this.$actions
.append( other
.$element
);
8702 other
.toggleFramed( false );
8705 if ( special
.primary
) {
8706 this.$actions
.append( special
.primary
.$element
);
8707 special
.primary
.toggleFramed( false );
8710 if ( !this.isOpening() ) {
8711 // If the dialog is currently opening, this will be called automatically soon.
8712 // This also calls #fitActions.
8718 * Fit action actions into columns or rows.
8720 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
8724 OO
.ui
.MessageDialog
.prototype.fitActions = function () {
8726 previous
= this.verticalActionLayout
,
8727 actions
= this.actions
.get();
8730 this.toggleVerticalActionLayout( false );
8731 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
8732 action
= actions
[ i
];
8733 if ( action
.$element
.innerWidth() < action
.$label
.outerWidth( true ) ) {
8734 this.toggleVerticalActionLayout( true );
8739 // Move the body out of the way of the foot
8740 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
8742 if ( this.verticalActionLayout
!== previous
) {
8743 // We changed the layout, window height might need to be updated.
8749 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
8750 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
8751 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
8752 * relevant. The ProcessDialog class is always extended and customized with the actions and content
8753 * required for each process.
8755 * The process dialog box consists of a header that visually represents the ‘working’ state of long
8756 * processes with an animation. The header contains the dialog title as well as
8757 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
8758 * a ‘primary’ action on the right (e.g., ‘Done’).
8760 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
8761 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
8764 * // Example: Creating and opening a process dialog window.
8765 * function MyProcessDialog( config ) {
8766 * MyProcessDialog.parent.call( this, config );
8768 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
8770 * MyProcessDialog.static.title = 'Process dialog';
8771 * MyProcessDialog.static.actions = [
8772 * { action: 'save', label: 'Done', flags: 'primary' },
8773 * { label: 'Cancel', flags: 'safe' }
8776 * MyProcessDialog.prototype.initialize = function () {
8777 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
8778 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
8779 * 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>' );
8780 * this.$body.append( this.content.$element );
8782 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
8783 * var dialog = this;
8785 * return new OO.ui.Process( function () {
8786 * dialog.close( { action: action } );
8789 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
8792 * var windowManager = new OO.ui.WindowManager();
8793 * $( 'body' ).append( windowManager.$element );
8795 * var dialog = new MyProcessDialog();
8796 * windowManager.addWindows( [ dialog ] );
8797 * windowManager.openWindow( dialog );
8799 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
8803 * @extends OO.ui.Dialog
8806 * @param {Object} [config] Configuration options
8808 OO
.ui
.ProcessDialog
= function OoUiProcessDialog( config
) {
8809 // Parent constructor
8810 OO
.ui
.ProcessDialog
.parent
.call( this, config
);
8813 this.fitOnOpen
= false;
8816 this.$element
.addClass( 'oo-ui-processDialog' );
8821 OO
.inheritClass( OO
.ui
.ProcessDialog
, OO
.ui
.Dialog
);
8826 * Handle dismiss button click events.
8832 OO
.ui
.ProcessDialog
.prototype.onDismissErrorButtonClick = function () {
8837 * Handle retry button click events.
8839 * Hides errors and then tries again.
8843 OO
.ui
.ProcessDialog
.prototype.onRetryButtonClick = function () {
8845 this.executeAction( this.currentAction
);
8851 OO
.ui
.ProcessDialog
.prototype.onActionResize = function ( action
) {
8852 if ( this.actions
.isSpecial( action
) ) {
8855 return OO
.ui
.ProcessDialog
.parent
.prototype.onActionResize
.call( this, action
);
8861 OO
.ui
.ProcessDialog
.prototype.initialize = function () {
8863 OO
.ui
.ProcessDialog
.parent
.prototype.initialize
.call( this );
8866 this.$navigation
= $( '<div>' );
8867 this.$location
= $( '<div>' );
8868 this.$safeActions
= $( '<div>' );
8869 this.$primaryActions
= $( '<div>' );
8870 this.$otherActions
= $( '<div>' );
8871 this.dismissButton
= new OO
.ui
.ButtonWidget( {
8872 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' )
8874 this.retryButton
= new OO
.ui
.ButtonWidget();
8875 this.$errors
= $( '<div>' );
8876 this.$errorsTitle
= $( '<div>' );
8879 this.dismissButton
.connect( this, { click
: 'onDismissErrorButtonClick' } );
8880 this.retryButton
.connect( this, { click
: 'onRetryButtonClick' } );
8883 this.title
.$element
.addClass( 'oo-ui-processDialog-title' );
8885 .append( this.title
.$element
)
8886 .addClass( 'oo-ui-processDialog-location' );
8887 this.$safeActions
.addClass( 'oo-ui-processDialog-actions-safe' );
8888 this.$primaryActions
.addClass( 'oo-ui-processDialog-actions-primary' );
8889 this.$otherActions
.addClass( 'oo-ui-processDialog-actions-other' );
8891 .addClass( 'oo-ui-processDialog-errors-title' )
8892 .text( OO
.ui
.msg( 'ooui-dialog-process-error' ) );
8894 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
8895 .append( this.$errorsTitle
, this.dismissButton
.$element
, this.retryButton
.$element
);
8897 .addClass( 'oo-ui-processDialog-content' )
8898 .append( this.$errors
);
8900 .addClass( 'oo-ui-processDialog-navigation' )
8901 .append( this.$safeActions
, this.$location
, this.$primaryActions
);
8902 this.$head
.append( this.$navigation
);
8903 this.$foot
.append( this.$otherActions
);
8909 OO
.ui
.ProcessDialog
.prototype.getActionWidgets = function ( actions
) {
8910 var i
, len
, widgets
= [];
8911 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
8913 new OO
.ui
.ActionWidget( $.extend( { framed
: true }, actions
[ i
] ) )
8922 OO
.ui
.ProcessDialog
.prototype.attachActions = function () {
8923 var i
, len
, other
, special
, others
;
8926 OO
.ui
.ProcessDialog
.parent
.prototype.attachActions
.call( this );
8928 special
= this.actions
.getSpecial();
8929 others
= this.actions
.getOthers();
8930 if ( special
.primary
) {
8931 this.$primaryActions
.append( special
.primary
.$element
);
8933 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
8934 other
= others
[ i
];
8935 this.$otherActions
.append( other
.$element
);
8937 if ( special
.safe
) {
8938 this.$safeActions
.append( special
.safe
.$element
);
8942 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
8948 OO
.ui
.ProcessDialog
.prototype.executeAction = function ( action
) {
8950 return OO
.ui
.ProcessDialog
.parent
.prototype.executeAction
.call( this, action
)
8951 .fail( function ( errors
) {
8952 process
.showErrors( errors
|| [] );
8959 OO
.ui
.ProcessDialog
.prototype.setDimensions = function () {
8961 OO
.ui
.ProcessDialog
.parent
.prototype.setDimensions
.apply( this, arguments
);
8967 * Fit label between actions.
8972 OO
.ui
.ProcessDialog
.prototype.fitLabel = function () {
8973 var safeWidth
, primaryWidth
, biggerWidth
, labelWidth
, navigationWidth
, leftWidth
, rightWidth
,
8974 size
= this.getSizeProperties();
8976 if ( typeof size
.width
!== 'number' ) {
8977 if ( this.isOpened() ) {
8978 navigationWidth
= this.$head
.width() - 20;
8979 } else if ( this.isOpening() ) {
8980 if ( !this.fitOnOpen
) {
8981 // Size is relative and the dialog isn't open yet, so wait.
8982 this.manager
.opening
.done( this.fitLabel
.bind( this ) );
8983 this.fitOnOpen
= true;
8990 navigationWidth
= size
.width
- 20;
8993 safeWidth
= this.$safeActions
.is( ':visible' ) ? this.$safeActions
.width() : 0;
8994 primaryWidth
= this.$primaryActions
.is( ':visible' ) ? this.$primaryActions
.width() : 0;
8995 biggerWidth
= Math
.max( safeWidth
, primaryWidth
);
8997 labelWidth
= this.title
.$element
.width();
8999 if ( 2 * biggerWidth
+ labelWidth
< navigationWidth
) {
9000 // We have enough space to center the label
9001 leftWidth
= rightWidth
= biggerWidth
;
9003 // Let's hope we at least have enough space not to overlap, because we can't wrap the label…
9004 if ( this.getDir() === 'ltr' ) {
9005 leftWidth
= safeWidth
;
9006 rightWidth
= primaryWidth
;
9008 leftWidth
= primaryWidth
;
9009 rightWidth
= safeWidth
;
9013 this.$location
.css( { paddingLeft
: leftWidth
, paddingRight
: rightWidth
} );
9019 * Handle errors that occurred during accept or reject processes.
9022 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
9024 OO
.ui
.ProcessDialog
.prototype.showErrors = function ( errors
) {
9025 var i
, len
, $item
, actions
,
9031 if ( errors
instanceof OO
.ui
.Error
) {
9032 errors
= [ errors
];
9035 for ( i
= 0, len
= errors
.length
; i
< len
; i
++ ) {
9036 if ( !errors
[ i
].isRecoverable() ) {
9037 recoverable
= false;
9039 if ( errors
[ i
].isWarning() ) {
9042 $item
= $( '<div>' )
9043 .addClass( 'oo-ui-processDialog-error' )
9044 .append( errors
[ i
].getMessage() );
9045 items
.push( $item
[ 0 ] );
9047 this.$errorItems
= $( items
);
9048 if ( recoverable
) {
9049 abilities
[ this.currentAction
] = true;
9050 // Copy the flags from the first matching action
9051 actions
= this.actions
.get( { actions
: this.currentAction
} );
9052 if ( actions
.length
) {
9053 this.retryButton
.clearFlags().setFlags( actions
[ 0 ].getFlags() );
9056 abilities
[ this.currentAction
] = false;
9057 this.actions
.setAbilities( abilities
);
9060 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-continue' ) );
9062 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-retry' ) );
9064 this.retryButton
.toggle( recoverable
);
9065 this.$errorsTitle
.after( this.$errorItems
);
9066 this.$errors
.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
9074 OO
.ui
.ProcessDialog
.prototype.hideErrors = function () {
9075 this.$errors
.addClass( 'oo-ui-element-hidden' );
9076 if ( this.$errorItems
) {
9077 this.$errorItems
.remove();
9078 this.$errorItems
= null;
9085 OO
.ui
.ProcessDialog
.prototype.getTeardownProcess = function ( data
) {
9087 return OO
.ui
.ProcessDialog
.parent
.prototype.getTeardownProcess
.call( this, data
)
9088 .first( function () {
9089 // Make sure to hide errors
9091 this.fitOnOpen
= false;
9096 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
9097 * which is a widget that is specified by reference before any optional configuration settings.
9099 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
9101 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9102 * A left-alignment is used for forms with many fields.
9103 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9104 * A right-alignment is used for long but familiar forms which users tab through,
9105 * verifying the current field with a quick glance at the label.
9106 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9107 * that users fill out from top to bottom.
9108 * - **inline**: The label is placed after the field-widget and aligned to the left.
9109 * An inline-alignment is best used with checkboxes or radio buttons.
9111 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
9112 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
9114 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9116 * @extends OO.ui.Layout
9117 * @mixins OO.ui.mixin.LabelElement
9118 * @mixins OO.ui.mixin.TitledElement
9121 * @param {OO.ui.Widget} fieldWidget Field widget
9122 * @param {Object} [config] Configuration options
9123 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
9124 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
9125 * The array may contain strings or OO.ui.HtmlSnippet instances.
9126 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
9127 * The array may contain strings or OO.ui.HtmlSnippet instances.
9128 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
9129 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
9130 * For important messages, you are advised to use `notices`, as they are always shown.
9132 * @throws {Error} An error is thrown if no widget is specified
9134 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
9135 var hasInputWidget
, div
;
9137 // Allow passing positional parameters inside the config object
9138 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
9139 config
= fieldWidget
;
9140 fieldWidget
= config
.fieldWidget
;
9143 // Make sure we have required constructor arguments
9144 if ( fieldWidget
=== undefined ) {
9145 throw new Error( 'Widget not found' );
9148 hasInputWidget
= fieldWidget
.constructor.static.supportsSimpleLabel
;
9150 // Configuration initialization
9151 config
= $.extend( { align
: 'left' }, config
);
9153 // Parent constructor
9154 OO
.ui
.FieldLayout
.parent
.call( this, config
);
9156 // Mixin constructors
9157 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9158 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
9161 this.fieldWidget
= fieldWidget
;
9164 this.$field
= $( '<div>' );
9165 this.$messages
= $( '<ul>' );
9166 this.$body
= $( '<' + ( hasInputWidget
? 'label' : 'div' ) + '>' );
9168 if ( config
.help
) {
9169 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
9170 classes
: [ 'oo-ui-fieldLayout-help' ],
9176 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
9177 div
.html( config
.help
.toString() );
9179 div
.text( config
.help
);
9181 this.popupButtonWidget
.getPopup().$body
.append(
9182 div
.addClass( 'oo-ui-fieldLayout-help-content' )
9184 this.$help
= this.popupButtonWidget
.$element
;
9186 this.$help
= $( [] );
9190 if ( hasInputWidget
) {
9191 this.$label
.on( 'click', this.onLabelClick
.bind( this ) );
9193 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
9197 .addClass( 'oo-ui-fieldLayout' )
9198 .append( this.$help
, this.$body
);
9199 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
9200 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
9202 .addClass( 'oo-ui-fieldLayout-field' )
9203 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget
.isDisabled() )
9204 .append( this.fieldWidget
.$element
);
9206 this.setErrors( config
.errors
|| [] );
9207 this.setNotices( config
.notices
|| [] );
9208 this.setAlignment( config
.align
);
9213 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
9214 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
9215 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
9220 * Handle field disable events.
9223 * @param {boolean} value Field is disabled
9225 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
9226 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
9230 * Handle label mouse click events.
9233 * @param {jQuery.Event} e Mouse click event
9235 OO
.ui
.FieldLayout
.prototype.onLabelClick = function () {
9236 this.fieldWidget
.simulateLabelClick();
9241 * Get the widget contained by the field.
9243 * @return {OO.ui.Widget} Field widget
9245 OO
.ui
.FieldLayout
.prototype.getField = function () {
9246 return this.fieldWidget
;
9251 * @param {string} kind 'error' or 'notice'
9252 * @param {string|OO.ui.HtmlSnippet} text
9255 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
9256 var $listItem
, $icon
, message
;
9257 $listItem
= $( '<li>' );
9258 if ( kind
=== 'error' ) {
9259 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
9260 } else if ( kind
=== 'notice' ) {
9261 $icon
= new OO
.ui
.IconWidget( { icon
: 'info' } ).$element
;
9265 message
= new OO
.ui
.LabelWidget( { label
: text
} );
9267 .append( $icon
, message
.$element
)
9268 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
9273 * Set the field alignment mode.
9276 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
9279 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
9280 if ( value
!== this.align
) {
9281 // Default to 'left'
9282 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
9286 if ( value
=== 'inline' ) {
9287 this.$body
.append( this.$field
, this.$label
);
9289 this.$body
.append( this.$label
, this.$field
);
9291 // Set classes. The following classes can be used here:
9292 // * oo-ui-fieldLayout-align-left
9293 // * oo-ui-fieldLayout-align-right
9294 // * oo-ui-fieldLayout-align-top
9295 // * oo-ui-fieldLayout-align-inline
9297 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
9299 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
9307 * Set the list of error messages.
9309 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
9310 * The array may contain strings or OO.ui.HtmlSnippet instances.
9313 OO
.ui
.FieldLayout
.prototype.setErrors = function ( errors
) {
9314 this.errors
= errors
.slice();
9315 this.updateMessages();
9320 * Set the list of notice messages.
9322 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
9323 * The array may contain strings or OO.ui.HtmlSnippet instances.
9326 OO
.ui
.FieldLayout
.prototype.setNotices = function ( notices
) {
9327 this.notices
= notices
.slice();
9328 this.updateMessages();
9333 * Update the rendering of error and notice messages.
9337 OO
.ui
.FieldLayout
.prototype.updateMessages = function () {
9339 this.$messages
.empty();
9341 if ( this.errors
.length
|| this.notices
.length
) {
9342 this.$body
.after( this.$messages
);
9344 this.$messages
.remove();
9348 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
9349 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
9351 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
9352 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
9357 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
9358 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
9359 * is required and is specified before any optional configuration settings.
9361 * Labels can be aligned in one of four ways:
9363 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9364 * A left-alignment is used for forms with many fields.
9365 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9366 * A right-alignment is used for long but familiar forms which users tab through,
9367 * verifying the current field with a quick glance at the label.
9368 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9369 * that users fill out from top to bottom.
9370 * - **inline**: The label is placed after the field-widget and aligned to the left.
9371 * An inline-alignment is best used with checkboxes or radio buttons.
9373 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
9374 * text is specified.
9377 * // Example of an ActionFieldLayout
9378 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
9379 * new OO.ui.TextInputWidget( {
9380 * placeholder: 'Field widget'
9382 * new OO.ui.ButtonWidget( {
9386 * label: 'An ActionFieldLayout. This label is aligned top',
9388 * help: 'This is help text'
9392 * $( 'body' ).append( actionFieldLayout.$element );
9395 * @extends OO.ui.FieldLayout
9398 * @param {OO.ui.Widget} fieldWidget Field widget
9399 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
9401 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
9402 // Allow passing positional parameters inside the config object
9403 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
9404 config
= fieldWidget
;
9405 fieldWidget
= config
.fieldWidget
;
9406 buttonWidget
= config
.buttonWidget
;
9409 // Parent constructor
9410 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
9413 this.buttonWidget
= buttonWidget
;
9414 this.$button
= $( '<div>' );
9415 this.$input
= $( '<div>' );
9419 .addClass( 'oo-ui-actionFieldLayout' );
9421 .addClass( 'oo-ui-actionFieldLayout-button' )
9422 .append( this.buttonWidget
.$element
);
9424 .addClass( 'oo-ui-actionFieldLayout-input' )
9425 .append( this.fieldWidget
.$element
);
9427 .append( this.$input
, this.$button
);
9432 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
9435 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
9436 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
9437 * configured with a label as well. For more information and examples,
9438 * please see the [OOjs UI documentation on MediaWiki][1].
9441 * // Example of a fieldset layout
9442 * var input1 = new OO.ui.TextInputWidget( {
9443 * placeholder: 'A text input field'
9446 * var input2 = new OO.ui.TextInputWidget( {
9447 * placeholder: 'A text input field'
9450 * var fieldset = new OO.ui.FieldsetLayout( {
9451 * label: 'Example of a fieldset layout'
9454 * fieldset.addItems( [
9455 * new OO.ui.FieldLayout( input1, {
9456 * label: 'Field One'
9458 * new OO.ui.FieldLayout( input2, {
9459 * label: 'Field Two'
9462 * $( 'body' ).append( fieldset.$element );
9464 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9467 * @extends OO.ui.Layout
9468 * @mixins OO.ui.mixin.IconElement
9469 * @mixins OO.ui.mixin.LabelElement
9470 * @mixins OO.ui.mixin.GroupElement
9473 * @param {Object} [config] Configuration options
9474 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
9476 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
9477 // Configuration initialization
9478 config
= config
|| {};
9480 // Parent constructor
9481 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
9483 // Mixin constructors
9484 OO
.ui
.mixin
.IconElement
.call( this, config
);
9485 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9486 OO
.ui
.mixin
.GroupElement
.call( this, config
);
9488 if ( config
.help
) {
9489 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
9490 classes
: [ 'oo-ui-fieldsetLayout-help' ],
9495 this.popupButtonWidget
.getPopup().$body
.append(
9497 .text( config
.help
)
9498 .addClass( 'oo-ui-fieldsetLayout-help-content' )
9500 this.$help
= this.popupButtonWidget
.$element
;
9502 this.$help
= $( [] );
9507 .addClass( 'oo-ui-fieldsetLayout' )
9508 .prepend( this.$help
, this.$icon
, this.$label
, this.$group
);
9509 if ( Array
.isArray( config
.items
) ) {
9510 this.addItems( config
.items
);
9516 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
9517 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
9518 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
9519 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
9522 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
9523 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
9524 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
9525 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9527 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
9528 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
9529 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
9530 * some fancier controls. Some controls have both regular and InputWidget variants, for example
9531 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
9532 * often have simplified APIs to match the capabilities of HTML forms.
9533 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
9535 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
9536 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9539 * // Example of a form layout that wraps a fieldset layout
9540 * var input1 = new OO.ui.TextInputWidget( {
9541 * placeholder: 'Username'
9543 * var input2 = new OO.ui.TextInputWidget( {
9544 * placeholder: 'Password',
9547 * var submit = new OO.ui.ButtonInputWidget( {
9551 * var fieldset = new OO.ui.FieldsetLayout( {
9552 * label: 'A form layout'
9554 * fieldset.addItems( [
9555 * new OO.ui.FieldLayout( input1, {
9556 * label: 'Username',
9559 * new OO.ui.FieldLayout( input2, {
9560 * label: 'Password',
9563 * new OO.ui.FieldLayout( submit )
9565 * var form = new OO.ui.FormLayout( {
9566 * items: [ fieldset ],
9567 * action: '/api/formhandler',
9570 * $( 'body' ).append( form.$element );
9573 * @extends OO.ui.Layout
9574 * @mixins OO.ui.mixin.GroupElement
9577 * @param {Object} [config] Configuration options
9578 * @cfg {string} [method] HTML form `method` attribute
9579 * @cfg {string} [action] HTML form `action` attribute
9580 * @cfg {string} [enctype] HTML form `enctype` attribute
9581 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
9583 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
9584 // Configuration initialization
9585 config
= config
|| {};
9587 // Parent constructor
9588 OO
.ui
.FormLayout
.parent
.call( this, config
);
9590 // Mixin constructors
9591 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
9594 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
9596 // Make sure the action is safe
9597 if ( config
.action
!== undefined && !OO
.ui
.isSafeUrl( config
.action
) ) {
9598 throw new Error( 'Potentially unsafe action provided: ' + config
.action
);
9603 .addClass( 'oo-ui-formLayout' )
9605 method
: config
.method
,
9606 action
: config
.action
,
9607 enctype
: config
.enctype
9609 if ( Array
.isArray( config
.items
) ) {
9610 this.addItems( config
.items
);
9616 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
9617 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
9622 * A 'submit' event is emitted when the form is submitted.
9627 /* Static Properties */
9629 OO
.ui
.FormLayout
.static.tagName
= 'form';
9634 * Handle form submit events.
9637 * @param {jQuery.Event} e Submit event
9640 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
9641 if ( this.emit( 'submit' ) ) {
9647 * 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)
9648 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
9651 * var menuLayout = new OO.ui.MenuLayout( {
9654 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9655 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9656 * select = new OO.ui.SelectWidget( {
9658 * new OO.ui.OptionWidget( {
9662 * new OO.ui.OptionWidget( {
9666 * new OO.ui.OptionWidget( {
9670 * new OO.ui.OptionWidget( {
9675 * } ).on( 'select', function ( item ) {
9676 * menuLayout.setMenuPosition( item.getData() );
9679 * menuLayout.$menu.append(
9680 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
9682 * menuLayout.$content.append(
9683 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
9685 * $( 'body' ).append( menuLayout.$element );
9687 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
9688 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
9689 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
9692 * .oo-ui-menuLayout-menu {
9696 * .oo-ui-menuLayout-content {
9704 * @extends OO.ui.Layout
9707 * @param {Object} [config] Configuration options
9708 * @cfg {boolean} [showMenu=true] Show menu
9709 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
9711 OO
.ui
.MenuLayout
= function OoUiMenuLayout( config
) {
9712 // Configuration initialization
9713 config
= $.extend( {
9715 menuPosition
: 'before'
9718 // Parent constructor
9719 OO
.ui
.MenuLayout
.parent
.call( this, config
);
9724 * @property {jQuery}
9726 this.$menu
= $( '<div>' );
9730 * @property {jQuery}
9732 this.$content
= $( '<div>' );
9736 .addClass( 'oo-ui-menuLayout-menu' );
9737 this.$content
.addClass( 'oo-ui-menuLayout-content' );
9739 .addClass( 'oo-ui-menuLayout' )
9740 .append( this.$content
, this.$menu
);
9741 this.setMenuPosition( config
.menuPosition
);
9742 this.toggleMenu( config
.showMenu
);
9747 OO
.inheritClass( OO
.ui
.MenuLayout
, OO
.ui
.Layout
);
9754 * @param {boolean} showMenu Show menu, omit to toggle
9757 OO
.ui
.MenuLayout
.prototype.toggleMenu = function ( showMenu
) {
9758 showMenu
= showMenu
=== undefined ? !this.showMenu
: !!showMenu
;
9760 if ( this.showMenu
!== showMenu
) {
9761 this.showMenu
= showMenu
;
9763 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu
)
9764 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu
);
9771 * Check if menu is visible
9773 * @return {boolean} Menu is visible
9775 OO
.ui
.MenuLayout
.prototype.isMenuVisible = function () {
9776 return this.showMenu
;
9780 * Set menu position.
9782 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
9783 * @throws {Error} If position value is not supported
9786 OO
.ui
.MenuLayout
.prototype.setMenuPosition = function ( position
) {
9787 this.$element
.removeClass( 'oo-ui-menuLayout-' + this.menuPosition
);
9788 this.menuPosition
= position
;
9789 this.$element
.addClass( 'oo-ui-menuLayout-' + position
);
9795 * Get menu position.
9797 * @return {string} Menu position
9799 OO
.ui
.MenuLayout
.prototype.getMenuPosition = function () {
9800 return this.menuPosition
;
9804 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
9805 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
9806 * through the pages and select which one to display. By default, only one page is
9807 * displayed at a time and the outline is hidden. When a user navigates to a new page,
9808 * the booklet layout automatically focuses on the first focusable element, unless the
9809 * default setting is changed. Optionally, booklets can be configured to show
9810 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
9813 * // Example of a BookletLayout that contains two PageLayouts.
9815 * function PageOneLayout( name, config ) {
9816 * PageOneLayout.parent.call( this, name, config );
9817 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
9819 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
9820 * PageOneLayout.prototype.setupOutlineItem = function () {
9821 * this.outlineItem.setLabel( 'Page One' );
9824 * function PageTwoLayout( name, config ) {
9825 * PageTwoLayout.parent.call( this, name, config );
9826 * this.$element.append( '<p>Second page</p>' );
9828 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
9829 * PageTwoLayout.prototype.setupOutlineItem = function () {
9830 * this.outlineItem.setLabel( 'Page Two' );
9833 * var page1 = new PageOneLayout( 'one' ),
9834 * page2 = new PageTwoLayout( 'two' );
9836 * var booklet = new OO.ui.BookletLayout( {
9840 * booklet.addPages ( [ page1, page2 ] );
9841 * $( 'body' ).append( booklet.$element );
9844 * @extends OO.ui.MenuLayout
9847 * @param {Object} [config] Configuration options
9848 * @cfg {boolean} [continuous=false] Show all pages, one after another
9849 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
9850 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
9851 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
9853 OO
.ui
.BookletLayout
= function OoUiBookletLayout( config
) {
9854 // Configuration initialization
9855 config
= config
|| {};
9857 // Parent constructor
9858 OO
.ui
.BookletLayout
.parent
.call( this, config
);
9861 this.currentPageName
= null;
9863 this.ignoreFocus
= false;
9864 this.stackLayout
= new OO
.ui
.StackLayout( { continuous
: !!config
.continuous
} );
9865 this.$content
.append( this.stackLayout
.$element
);
9866 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
9867 this.outlineVisible
= false;
9868 this.outlined
= !!config
.outlined
;
9869 if ( this.outlined
) {
9870 this.editable
= !!config
.editable
;
9871 this.outlineControlsWidget
= null;
9872 this.outlineSelectWidget
= new OO
.ui
.OutlineSelectWidget();
9873 this.outlinePanel
= new OO
.ui
.PanelLayout( { scrollable
: true } );
9874 this.$menu
.append( this.outlinePanel
.$element
);
9875 this.outlineVisible
= true;
9876 if ( this.editable
) {
9877 this.outlineControlsWidget
= new OO
.ui
.OutlineControlsWidget(
9878 this.outlineSelectWidget
9882 this.toggleMenu( this.outlined
);
9885 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
9886 if ( this.outlined
) {
9887 this.outlineSelectWidget
.connect( this, { select
: 'onOutlineSelectWidgetSelect' } );
9888 this.scrolling
= false;
9889 this.stackLayout
.connect( this, { visibleItemChange
: 'onStackLayoutVisibleItemChange' } );
9891 if ( this.autoFocus
) {
9892 // Event 'focus' does not bubble, but 'focusin' does
9893 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
9897 this.$element
.addClass( 'oo-ui-bookletLayout' );
9898 this.stackLayout
.$element
.addClass( 'oo-ui-bookletLayout-stackLayout' );
9899 if ( this.outlined
) {
9900 this.outlinePanel
.$element
9901 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
9902 .append( this.outlineSelectWidget
.$element
);
9903 if ( this.editable
) {
9904 this.outlinePanel
.$element
9905 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
9906 .append( this.outlineControlsWidget
.$element
);
9913 OO
.inheritClass( OO
.ui
.BookletLayout
, OO
.ui
.MenuLayout
);
9918 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
9920 * @param {OO.ui.PageLayout} page Current page
9924 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
9927 * @param {OO.ui.PageLayout[]} page Added pages
9928 * @param {number} index Index pages were added at
9932 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
9933 * {@link #removePages removed} from the booklet.
9936 * @param {OO.ui.PageLayout[]} pages Removed pages
9942 * Handle stack layout focus.
9945 * @param {jQuery.Event} e Focusin event
9947 OO
.ui
.BookletLayout
.prototype.onStackLayoutFocus = function ( e
) {
9950 // Find the page that an element was focused within
9951 $target
= $( e
.target
).closest( '.oo-ui-pageLayout' );
9952 for ( name
in this.pages
) {
9953 // Check for page match, exclude current page to find only page changes
9954 if ( this.pages
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentPageName
) {
9955 this.setPage( name
);
9962 * Handle visibleItemChange events from the stackLayout
9964 * The next visible page is set as the current page by selecting it
9967 * @param {OO.ui.PageLayout} page The next visible page in the layout
9969 OO
.ui
.BookletLayout
.prototype.onStackLayoutVisibleItemChange = function ( page
) {
9970 // Set a flag to so that the resulting call to #onStackLayoutSet doesn't
9971 // try and scroll the item into view again.
9972 this.scrolling
= true;
9973 this.outlineSelectWidget
.selectItemByData( page
.getName() );
9974 this.scrolling
= false;
9978 * Handle stack layout set events.
9981 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
9983 OO
.ui
.BookletLayout
.prototype.onStackLayoutSet = function ( page
) {
9985 if ( !this.scrolling
&& page
) {
9986 page
.scrollElementIntoView( { complete: function () {
9987 if ( layout
.autoFocus
) {
9995 * Focus the first input in the current page.
9997 * If no page is selected, the first selectable page will be selected.
9998 * If the focus is already in an element on the current page, nothing will happen.
9999 * @param {number} [itemIndex] A specific item to focus on
10001 OO
.ui
.BookletLayout
.prototype.focus = function ( itemIndex
) {
10003 items
= this.stackLayout
.getItems();
10005 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
10006 page
= items
[ itemIndex
];
10008 page
= this.stackLayout
.getCurrentItem();
10011 if ( !page
&& this.outlined
) {
10012 this.selectFirstSelectablePage();
10013 page
= this.stackLayout
.getCurrentItem();
10018 // Only change the focus if is not already in the current page
10019 if ( !OO
.ui
.contains( page
.$element
[ 0 ], this.getElementDocument().activeElement
, true ) ) {
10025 * Find the first focusable input in the booklet layout and focus
10028 OO
.ui
.BookletLayout
.prototype.focusFirstFocusable = function () {
10029 OO
.ui
.findFocusable( this.stackLayout
.$element
).focus();
10033 * Handle outline widget select events.
10036 * @param {OO.ui.OptionWidget|null} item Selected item
10038 OO
.ui
.BookletLayout
.prototype.onOutlineSelectWidgetSelect = function ( item
) {
10040 this.setPage( item
.getData() );
10045 * Check if booklet has an outline.
10047 * @return {boolean} Booklet has an outline
10049 OO
.ui
.BookletLayout
.prototype.isOutlined = function () {
10050 return this.outlined
;
10054 * Check if booklet has editing controls.
10056 * @return {boolean} Booklet is editable
10058 OO
.ui
.BookletLayout
.prototype.isEditable = function () {
10059 return this.editable
;
10063 * Check if booklet has a visible outline.
10065 * @return {boolean} Outline is visible
10067 OO
.ui
.BookletLayout
.prototype.isOutlineVisible = function () {
10068 return this.outlined
&& this.outlineVisible
;
10072 * Hide or show the outline.
10074 * @param {boolean} [show] Show outline, omit to invert current state
10077 OO
.ui
.BookletLayout
.prototype.toggleOutline = function ( show
) {
10078 if ( this.outlined
) {
10079 show
= show
=== undefined ? !this.outlineVisible
: !!show
;
10080 this.outlineVisible
= show
;
10081 this.toggleMenu( show
);
10088 * Get the page closest to the specified page.
10090 * @param {OO.ui.PageLayout} page Page to use as a reference point
10091 * @return {OO.ui.PageLayout|null} Page closest to the specified page
10093 OO
.ui
.BookletLayout
.prototype.getClosestPage = function ( page
) {
10094 var next
, prev
, level
,
10095 pages
= this.stackLayout
.getItems(),
10096 index
= pages
.indexOf( page
);
10098 if ( index
!== -1 ) {
10099 next
= pages
[ index
+ 1 ];
10100 prev
= pages
[ index
- 1 ];
10101 // Prefer adjacent pages at the same level
10102 if ( this.outlined
) {
10103 level
= this.outlineSelectWidget
.getItemFromData( page
.getName() ).getLevel();
10106 level
=== this.outlineSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
10112 level
=== this.outlineSelectWidget
.getItemFromData( next
.getName() ).getLevel()
10118 return prev
|| next
|| null;
10122 * Get the outline widget.
10124 * If the booklet is not outlined, the method will return `null`.
10126 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
10128 OO
.ui
.BookletLayout
.prototype.getOutline = function () {
10129 return this.outlineSelectWidget
;
10133 * Get the outline controls widget.
10135 * If the outline is not editable, the method will return `null`.
10137 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
10139 OO
.ui
.BookletLayout
.prototype.getOutlineControls = function () {
10140 return this.outlineControlsWidget
;
10144 * Get a page by its symbolic name.
10146 * @param {string} name Symbolic name of page
10147 * @return {OO.ui.PageLayout|undefined} Page, if found
10149 OO
.ui
.BookletLayout
.prototype.getPage = function ( name
) {
10150 return this.pages
[ name
];
10154 * Get the current page.
10156 * @return {OO.ui.PageLayout|undefined} Current page, if found
10158 OO
.ui
.BookletLayout
.prototype.getCurrentPage = function () {
10159 var name
= this.getCurrentPageName();
10160 return name
? this.getPage( name
) : undefined;
10164 * Get the symbolic name of the current page.
10166 * @return {string|null} Symbolic name of the current page
10168 OO
.ui
.BookletLayout
.prototype.getCurrentPageName = function () {
10169 return this.currentPageName
;
10173 * Add pages to the booklet layout
10175 * When pages are added with the same names as existing pages, the existing pages will be
10176 * automatically removed before the new pages are added.
10178 * @param {OO.ui.PageLayout[]} pages Pages to add
10179 * @param {number} index Index of the insertion point
10183 OO
.ui
.BookletLayout
.prototype.addPages = function ( pages
, index
) {
10184 var i
, len
, name
, page
, item
, currentIndex
,
10185 stackLayoutPages
= this.stackLayout
.getItems(),
10189 // Remove pages with same names
10190 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
10192 name
= page
.getName();
10194 if ( Object
.prototype.hasOwnProperty
.call( this.pages
, name
) ) {
10195 // Correct the insertion index
10196 currentIndex
= stackLayoutPages
.indexOf( this.pages
[ name
] );
10197 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
10200 remove
.push( this.pages
[ name
] );
10203 if ( remove
.length
) {
10204 this.removePages( remove
);
10208 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
10210 name
= page
.getName();
10211 this.pages
[ page
.getName() ] = page
;
10212 if ( this.outlined
) {
10213 item
= new OO
.ui
.OutlineOptionWidget( { data
: name
} );
10214 page
.setOutlineItem( item
);
10215 items
.push( item
);
10219 if ( this.outlined
&& items
.length
) {
10220 this.outlineSelectWidget
.addItems( items
, index
);
10221 this.selectFirstSelectablePage();
10223 this.stackLayout
.addItems( pages
, index
);
10224 this.emit( 'add', pages
, index
);
10230 * Remove the specified pages from the booklet layout.
10232 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
10234 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
10238 OO
.ui
.BookletLayout
.prototype.removePages = function ( pages
) {
10239 var i
, len
, name
, page
,
10242 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
10244 name
= page
.getName();
10245 delete this.pages
[ name
];
10246 if ( this.outlined
) {
10247 items
.push( this.outlineSelectWidget
.getItemFromData( name
) );
10248 page
.setOutlineItem( null );
10251 if ( this.outlined
&& items
.length
) {
10252 this.outlineSelectWidget
.removeItems( items
);
10253 this.selectFirstSelectablePage();
10255 this.stackLayout
.removeItems( pages
);
10256 this.emit( 'remove', pages
);
10262 * Clear all pages from the booklet layout.
10264 * To remove only a subset of pages from the booklet, use the #removePages method.
10269 OO
.ui
.BookletLayout
.prototype.clearPages = function () {
10271 pages
= this.stackLayout
.getItems();
10274 this.currentPageName
= null;
10275 if ( this.outlined
) {
10276 this.outlineSelectWidget
.clearItems();
10277 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
10278 pages
[ i
].setOutlineItem( null );
10281 this.stackLayout
.clearItems();
10283 this.emit( 'remove', pages
);
10289 * Set the current page by symbolic name.
10292 * @param {string} name Symbolic name of page
10294 OO
.ui
.BookletLayout
.prototype.setPage = function ( name
) {
10297 page
= this.pages
[ name
],
10298 previousPage
= this.currentPageName
&& this.pages
[ this.currentPageName
];
10300 if ( name
!== this.currentPageName
) {
10301 if ( this.outlined
) {
10302 selectedItem
= this.outlineSelectWidget
.getSelectedItem();
10303 if ( selectedItem
&& selectedItem
.getData() !== name
) {
10304 this.outlineSelectWidget
.selectItemByData( name
);
10308 if ( previousPage
) {
10309 previousPage
.setActive( false );
10310 // Blur anything focused if the next page doesn't have anything focusable.
10311 // This is not needed if the next page has something focusable (because once it is focused
10312 // this blur happens automatically). If the layout is non-continuous, this check is
10313 // meaningless because the next page is not visible yet and thus can't hold focus.
10316 this.stackLayout
.continuous
&&
10317 OO
.ui
.findFocusable( page
.$element
).length
!== 0
10319 $focused
= previousPage
.$element
.find( ':focus' );
10320 if ( $focused
.length
) {
10321 $focused
[ 0 ].blur();
10325 this.currentPageName
= name
;
10326 page
.setActive( true );
10327 this.stackLayout
.setItem( page
);
10328 if ( !this.stackLayout
.continuous
&& previousPage
) {
10329 // This should not be necessary, since any inputs on the previous page should have been
10330 // blurred when it was hidden, but browsers are not very consistent about this.
10331 $focused
= previousPage
.$element
.find( ':focus' );
10332 if ( $focused
.length
) {
10333 $focused
[ 0 ].blur();
10336 this.emit( 'set', page
);
10342 * Select the first selectable page.
10346 OO
.ui
.BookletLayout
.prototype.selectFirstSelectablePage = function () {
10347 if ( !this.outlineSelectWidget
.getSelectedItem() ) {
10348 this.outlineSelectWidget
.selectItem( this.outlineSelectWidget
.getFirstSelectableItem() );
10355 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
10356 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
10357 * select which one to display. By default, only one card is displayed at a time. When a user
10358 * navigates to a new card, the index layout automatically focuses on the first focusable element,
10359 * unless the default setting is changed.
10361 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
10364 * // Example of a IndexLayout that contains two CardLayouts.
10366 * function CardOneLayout( name, config ) {
10367 * CardOneLayout.parent.call( this, name, config );
10368 * this.$element.append( '<p>First card</p>' );
10370 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
10371 * CardOneLayout.prototype.setupTabItem = function () {
10372 * this.tabItem.setLabel( 'Card one' );
10375 * var card1 = new CardOneLayout( 'one' ),
10376 * card2 = new CardLayout( 'two', { label: 'Card two' } );
10378 * card2.$element.append( '<p>Second card</p>' );
10380 * var index = new OO.ui.IndexLayout();
10382 * index.addCards ( [ card1, card2 ] );
10383 * $( 'body' ).append( index.$element );
10386 * @extends OO.ui.MenuLayout
10389 * @param {Object} [config] Configuration options
10390 * @cfg {boolean} [continuous=false] Show all cards, one after another
10391 * @cfg {boolean} [expanded=true] Expand the content panel to fill the entire parent element.
10392 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
10394 OO
.ui
.IndexLayout
= function OoUiIndexLayout( config
) {
10395 // Configuration initialization
10396 config
= $.extend( {}, config
, { menuPosition
: 'top' } );
10398 // Parent constructor
10399 OO
.ui
.IndexLayout
.parent
.call( this, config
);
10402 this.currentCardName
= null;
10404 this.ignoreFocus
= false;
10405 this.stackLayout
= new OO
.ui
.StackLayout( {
10406 continuous
: !!config
.continuous
,
10407 expanded
: config
.expanded
10409 this.$content
.append( this.stackLayout
.$element
);
10410 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
10412 this.tabSelectWidget
= new OO
.ui
.TabSelectWidget();
10413 this.tabPanel
= new OO
.ui
.PanelLayout();
10414 this.$menu
.append( this.tabPanel
.$element
);
10416 this.toggleMenu( true );
10419 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
10420 this.tabSelectWidget
.connect( this, { select
: 'onTabSelectWidgetSelect' } );
10421 if ( this.autoFocus
) {
10422 // Event 'focus' does not bubble, but 'focusin' does
10423 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
10427 this.$element
.addClass( 'oo-ui-indexLayout' );
10428 this.stackLayout
.$element
.addClass( 'oo-ui-indexLayout-stackLayout' );
10429 this.tabPanel
.$element
10430 .addClass( 'oo-ui-indexLayout-tabPanel' )
10431 .append( this.tabSelectWidget
.$element
);
10436 OO
.inheritClass( OO
.ui
.IndexLayout
, OO
.ui
.MenuLayout
);
10441 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
10443 * @param {OO.ui.CardLayout} card Current card
10447 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
10450 * @param {OO.ui.CardLayout[]} card Added cards
10451 * @param {number} index Index cards were added at
10455 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
10456 * {@link #removeCards removed} from the index.
10459 * @param {OO.ui.CardLayout[]} cards Removed cards
10465 * Handle stack layout focus.
10468 * @param {jQuery.Event} e Focusin event
10470 OO
.ui
.IndexLayout
.prototype.onStackLayoutFocus = function ( e
) {
10473 // Find the card that an element was focused within
10474 $target
= $( e
.target
).closest( '.oo-ui-cardLayout' );
10475 for ( name
in this.cards
) {
10476 // Check for card match, exclude current card to find only card changes
10477 if ( this.cards
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentCardName
) {
10478 this.setCard( name
);
10485 * Handle stack layout set events.
10488 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
10490 OO
.ui
.IndexLayout
.prototype.onStackLayoutSet = function ( card
) {
10493 card
.scrollElementIntoView( { complete: function () {
10494 if ( layout
.autoFocus
) {
10502 * Focus the first input in the current card.
10504 * If no card is selected, the first selectable card will be selected.
10505 * If the focus is already in an element on the current card, nothing will happen.
10506 * @param {number} [itemIndex] A specific item to focus on
10508 OO
.ui
.IndexLayout
.prototype.focus = function ( itemIndex
) {
10510 items
= this.stackLayout
.getItems();
10512 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
10513 card
= items
[ itemIndex
];
10515 card
= this.stackLayout
.getCurrentItem();
10519 this.selectFirstSelectableCard();
10520 card
= this.stackLayout
.getCurrentItem();
10525 // Only change the focus if is not already in the current page
10526 if ( !OO
.ui
.contains( card
.$element
[ 0 ], this.getElementDocument().activeElement
, true ) ) {
10532 * Find the first focusable input in the index layout and focus
10535 OO
.ui
.IndexLayout
.prototype.focusFirstFocusable = function () {
10536 OO
.ui
.findFocusable( this.stackLayout
.$element
).focus();
10540 * Handle tab widget select events.
10543 * @param {OO.ui.OptionWidget|null} item Selected item
10545 OO
.ui
.IndexLayout
.prototype.onTabSelectWidgetSelect = function ( item
) {
10547 this.setCard( item
.getData() );
10552 * Get the card closest to the specified card.
10554 * @param {OO.ui.CardLayout} card Card to use as a reference point
10555 * @return {OO.ui.CardLayout|null} Card closest to the specified card
10557 OO
.ui
.IndexLayout
.prototype.getClosestCard = function ( card
) {
10558 var next
, prev
, level
,
10559 cards
= this.stackLayout
.getItems(),
10560 index
= cards
.indexOf( card
);
10562 if ( index
!== -1 ) {
10563 next
= cards
[ index
+ 1 ];
10564 prev
= cards
[ index
- 1 ];
10565 // Prefer adjacent cards at the same level
10566 level
= this.tabSelectWidget
.getItemFromData( card
.getName() ).getLevel();
10569 level
=== this.tabSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
10575 level
=== this.tabSelectWidget
.getItemFromData( next
.getName() ).getLevel()
10580 return prev
|| next
|| null;
10584 * Get the tabs widget.
10586 * @return {OO.ui.TabSelectWidget} Tabs widget
10588 OO
.ui
.IndexLayout
.prototype.getTabs = function () {
10589 return this.tabSelectWidget
;
10593 * Get a card by its symbolic name.
10595 * @param {string} name Symbolic name of card
10596 * @return {OO.ui.CardLayout|undefined} Card, if found
10598 OO
.ui
.IndexLayout
.prototype.getCard = function ( name
) {
10599 return this.cards
[ name
];
10603 * Get the current card.
10605 * @return {OO.ui.CardLayout|undefined} Current card, if found
10607 OO
.ui
.IndexLayout
.prototype.getCurrentCard = function () {
10608 var name
= this.getCurrentCardName();
10609 return name
? this.getCard( name
) : undefined;
10613 * Get the symbolic name of the current card.
10615 * @return {string|null} Symbolic name of the current card
10617 OO
.ui
.IndexLayout
.prototype.getCurrentCardName = function () {
10618 return this.currentCardName
;
10622 * Add cards to the index layout
10624 * When cards are added with the same names as existing cards, the existing cards will be
10625 * automatically removed before the new cards are added.
10627 * @param {OO.ui.CardLayout[]} cards Cards to add
10628 * @param {number} index Index of the insertion point
10632 OO
.ui
.IndexLayout
.prototype.addCards = function ( cards
, index
) {
10633 var i
, len
, name
, card
, item
, currentIndex
,
10634 stackLayoutCards
= this.stackLayout
.getItems(),
10638 // Remove cards with same names
10639 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10641 name
= card
.getName();
10643 if ( Object
.prototype.hasOwnProperty
.call( this.cards
, name
) ) {
10644 // Correct the insertion index
10645 currentIndex
= stackLayoutCards
.indexOf( this.cards
[ name
] );
10646 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
10649 remove
.push( this.cards
[ name
] );
10652 if ( remove
.length
) {
10653 this.removeCards( remove
);
10657 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10659 name
= card
.getName();
10660 this.cards
[ card
.getName() ] = card
;
10661 item
= new OO
.ui
.TabOptionWidget( { data
: name
} );
10662 card
.setTabItem( item
);
10663 items
.push( item
);
10666 if ( items
.length
) {
10667 this.tabSelectWidget
.addItems( items
, index
);
10668 this.selectFirstSelectableCard();
10670 this.stackLayout
.addItems( cards
, index
);
10671 this.emit( 'add', cards
, index
);
10677 * Remove the specified cards from the index layout.
10679 * To remove all cards from the index, you may wish to use the #clearCards method instead.
10681 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
10685 OO
.ui
.IndexLayout
.prototype.removeCards = function ( cards
) {
10686 var i
, len
, name
, card
,
10689 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10691 name
= card
.getName();
10692 delete this.cards
[ name
];
10693 items
.push( this.tabSelectWidget
.getItemFromData( name
) );
10694 card
.setTabItem( null );
10696 if ( items
.length
) {
10697 this.tabSelectWidget
.removeItems( items
);
10698 this.selectFirstSelectableCard();
10700 this.stackLayout
.removeItems( cards
);
10701 this.emit( 'remove', cards
);
10707 * Clear all cards from the index layout.
10709 * To remove only a subset of cards from the index, use the #removeCards method.
10714 OO
.ui
.IndexLayout
.prototype.clearCards = function () {
10716 cards
= this.stackLayout
.getItems();
10719 this.currentCardName
= null;
10720 this.tabSelectWidget
.clearItems();
10721 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10722 cards
[ i
].setTabItem( null );
10724 this.stackLayout
.clearItems();
10726 this.emit( 'remove', cards
);
10732 * Set the current card by symbolic name.
10735 * @param {string} name Symbolic name of card
10737 OO
.ui
.IndexLayout
.prototype.setCard = function ( name
) {
10740 card
= this.cards
[ name
],
10741 previousCard
= this.currentCardName
&& this.cards
[ this.currentCardName
];
10743 if ( name
!== this.currentCardName
) {
10744 selectedItem
= this.tabSelectWidget
.getSelectedItem();
10745 if ( selectedItem
&& selectedItem
.getData() !== name
) {
10746 this.tabSelectWidget
.selectItemByData( name
);
10749 if ( previousCard
) {
10750 previousCard
.setActive( false );
10751 // Blur anything focused if the next card doesn't have anything focusable.
10752 // This is not needed if the next card has something focusable (because once it is focused
10753 // this blur happens automatically). If the layout is non-continuous, this check is
10754 // meaningless because the next card is not visible yet and thus can't hold focus.
10757 this.stackLayout
.continuous
&&
10758 OO
.ui
.findFocusable( card
.$element
).length
!== 0
10760 $focused
= previousCard
.$element
.find( ':focus' );
10761 if ( $focused
.length
) {
10762 $focused
[ 0 ].blur();
10766 this.currentCardName
= name
;
10767 card
.setActive( true );
10768 this.stackLayout
.setItem( card
);
10769 if ( !this.stackLayout
.continuous
&& previousCard
) {
10770 // This should not be necessary, since any inputs on the previous card should have been
10771 // blurred when it was hidden, but browsers are not very consistent about this.
10772 $focused
= previousCard
.$element
.find( ':focus' );
10773 if ( $focused
.length
) {
10774 $focused
[ 0 ].blur();
10777 this.emit( 'set', card
);
10783 * Select the first selectable card.
10787 OO
.ui
.IndexLayout
.prototype.selectFirstSelectableCard = function () {
10788 if ( !this.tabSelectWidget
.getSelectedItem() ) {
10789 this.tabSelectWidget
.selectItem( this.tabSelectWidget
.getFirstSelectableItem() );
10796 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10797 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10800 * // Example of a panel layout
10801 * var panel = new OO.ui.PanelLayout( {
10805 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10807 * $( 'body' ).append( panel.$element );
10810 * @extends OO.ui.Layout
10813 * @param {Object} [config] Configuration options
10814 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10815 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10816 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10817 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10819 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
10820 // Configuration initialization
10821 config
= $.extend( {
10828 // Parent constructor
10829 OO
.ui
.PanelLayout
.parent
.call( this, config
);
10832 this.$element
.addClass( 'oo-ui-panelLayout' );
10833 if ( config
.scrollable
) {
10834 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
10836 if ( config
.padded
) {
10837 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
10839 if ( config
.expanded
) {
10840 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
10842 if ( config
.framed
) {
10843 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
10849 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
10854 * Focus the panel layout
10856 * The default implementation just focuses the first focusable element in the panel
10858 OO
.ui
.PanelLayout
.prototype.focus = function () {
10859 OO
.ui
.findFocusable( this.$element
).focus();
10863 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
10864 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
10865 * rather extended to include the required content and functionality.
10867 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
10868 * item is customized (with a label) using the #setupTabItem method. See
10869 * {@link OO.ui.IndexLayout IndexLayout} for an example.
10872 * @extends OO.ui.PanelLayout
10875 * @param {string} name Unique symbolic name of card
10876 * @param {Object} [config] Configuration options
10877 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] Label for card's tab
10879 OO
.ui
.CardLayout
= function OoUiCardLayout( name
, config
) {
10880 // Allow passing positional parameters inside the config object
10881 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
10883 name
= config
.name
;
10886 // Configuration initialization
10887 config
= $.extend( { scrollable
: true }, config
);
10889 // Parent constructor
10890 OO
.ui
.CardLayout
.parent
.call( this, config
);
10894 this.label
= config
.label
;
10895 this.tabItem
= null;
10896 this.active
= false;
10899 this.$element
.addClass( 'oo-ui-cardLayout' );
10904 OO
.inheritClass( OO
.ui
.CardLayout
, OO
.ui
.PanelLayout
);
10909 * An 'active' event is emitted when the card becomes active. Cards become active when they are
10910 * shown in a index layout that is configured to display only one card at a time.
10913 * @param {boolean} active Card is active
10919 * Get the symbolic name of the card.
10921 * @return {string} Symbolic name of card
10923 OO
.ui
.CardLayout
.prototype.getName = function () {
10928 * Check if card is active.
10930 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
10931 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
10933 * @return {boolean} Card is active
10935 OO
.ui
.CardLayout
.prototype.isActive = function () {
10936 return this.active
;
10942 * The tab item allows users to access the card from the index's tab
10943 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
10945 * @return {OO.ui.TabOptionWidget|null} Tab option widget
10947 OO
.ui
.CardLayout
.prototype.getTabItem = function () {
10948 return this.tabItem
;
10952 * Set or unset the tab item.
10954 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
10955 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
10956 * level), use #setupTabItem instead of this method.
10958 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
10961 OO
.ui
.CardLayout
.prototype.setTabItem = function ( tabItem
) {
10962 this.tabItem
= tabItem
|| null;
10964 this.setupTabItem();
10970 * Set up the tab item.
10972 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
10973 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
10974 * the #setTabItem method instead.
10976 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
10979 OO
.ui
.CardLayout
.prototype.setupTabItem = function () {
10980 if ( this.label
) {
10981 this.tabItem
.setLabel( this.label
);
10987 * Set the card to its 'active' state.
10989 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
10990 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
10991 * context, setting the active state on a card does nothing.
10993 * @param {boolean} value Card is active
10996 OO
.ui
.CardLayout
.prototype.setActive = function ( active
) {
10999 if ( active
!== this.active
) {
11000 this.active
= active
;
11001 this.$element
.toggleClass( 'oo-ui-cardLayout-active', this.active
);
11002 this.emit( 'active', this.active
);
11007 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
11008 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
11009 * rather extended to include the required content and functionality.
11011 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
11012 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
11013 * {@link OO.ui.BookletLayout BookletLayout} for an example.
11016 * @extends OO.ui.PanelLayout
11019 * @param {string} name Unique symbolic name of page
11020 * @param {Object} [config] Configuration options
11022 OO
.ui
.PageLayout
= function OoUiPageLayout( name
, config
) {
11023 // Allow passing positional parameters inside the config object
11024 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
11026 name
= config
.name
;
11029 // Configuration initialization
11030 config
= $.extend( { scrollable
: true }, config
);
11032 // Parent constructor
11033 OO
.ui
.PageLayout
.parent
.call( this, config
);
11037 this.outlineItem
= null;
11038 this.active
= false;
11041 this.$element
.addClass( 'oo-ui-pageLayout' );
11046 OO
.inheritClass( OO
.ui
.PageLayout
, OO
.ui
.PanelLayout
);
11051 * An 'active' event is emitted when the page becomes active. Pages become active when they are
11052 * shown in a booklet layout that is configured to display only one page at a time.
11055 * @param {boolean} active Page is active
11061 * Get the symbolic name of the page.
11063 * @return {string} Symbolic name of page
11065 OO
.ui
.PageLayout
.prototype.getName = function () {
11070 * Check if page is active.
11072 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
11073 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
11075 * @return {boolean} Page is active
11077 OO
.ui
.PageLayout
.prototype.isActive = function () {
11078 return this.active
;
11082 * Get outline item.
11084 * The outline item allows users to access the page from the booklet's outline
11085 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
11087 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
11089 OO
.ui
.PageLayout
.prototype.getOutlineItem = function () {
11090 return this.outlineItem
;
11094 * Set or unset the outline item.
11096 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
11097 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
11098 * level), use #setupOutlineItem instead of this method.
11100 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
11103 OO
.ui
.PageLayout
.prototype.setOutlineItem = function ( outlineItem
) {
11104 this.outlineItem
= outlineItem
|| null;
11105 if ( outlineItem
) {
11106 this.setupOutlineItem();
11112 * Set up the outline item.
11114 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
11115 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
11116 * the #setOutlineItem method instead.
11118 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
11121 OO
.ui
.PageLayout
.prototype.setupOutlineItem = function () {
11126 * Set the page to its 'active' state.
11128 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
11129 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
11130 * context, setting the active state on a page does nothing.
11132 * @param {boolean} value Page is active
11135 OO
.ui
.PageLayout
.prototype.setActive = function ( active
) {
11138 if ( active
!== this.active
) {
11139 this.active
= active
;
11140 this.$element
.toggleClass( 'oo-ui-pageLayout-active', active
);
11141 this.emit( 'active', this.active
);
11146 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
11147 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
11148 * by setting the #continuous option to 'true'.
11151 * // A stack layout with two panels, configured to be displayed continously
11152 * var myStack = new OO.ui.StackLayout( {
11154 * new OO.ui.PanelLayout( {
11155 * $content: $( '<p>Panel One</p>' ),
11159 * new OO.ui.PanelLayout( {
11160 * $content: $( '<p>Panel Two</p>' ),
11167 * $( 'body' ).append( myStack.$element );
11170 * @extends OO.ui.PanelLayout
11171 * @mixins OO.ui.mixin.GroupElement
11174 * @param {Object} [config] Configuration options
11175 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
11176 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
11178 OO
.ui
.StackLayout
= function OoUiStackLayout( config
) {
11179 // Configuration initialization
11180 config
= $.extend( { scrollable
: true }, config
);
11182 // Parent constructor
11183 OO
.ui
.StackLayout
.parent
.call( this, config
);
11185 // Mixin constructors
11186 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11189 this.currentItem
= null;
11190 this.continuous
= !!config
.continuous
;
11193 this.$element
.addClass( 'oo-ui-stackLayout' );
11194 if ( this.continuous
) {
11195 this.$element
.addClass( 'oo-ui-stackLayout-continuous' );
11196 this.$element
.on( 'scroll', OO
.ui
.debounce( this.onScroll
.bind( this ), 250 ) );
11198 if ( Array
.isArray( config
.items
) ) {
11199 this.addItems( config
.items
);
11205 OO
.inheritClass( OO
.ui
.StackLayout
, OO
.ui
.PanelLayout
);
11206 OO
.mixinClass( OO
.ui
.StackLayout
, OO
.ui
.mixin
.GroupElement
);
11211 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
11212 * {@link #clearItems cleared} or {@link #setItem displayed}.
11215 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
11219 * When used in continuous mode, this event is emitted when the user scrolls down
11220 * far enough such that currentItem is no longer visible.
11222 * @event visibleItemChange
11223 * @param {OO.ui.PanelLayout} panel The next visible item in the layout
11229 * Handle scroll events from the layout element
11231 * @param {jQuery.Event} e
11232 * @fires visibleItemChange
11234 OO
.ui
.StackLayout
.prototype.onScroll = function () {
11236 len
= this.items
.length
,
11237 currentIndex
= this.items
.indexOf( this.currentItem
),
11238 newIndex
= currentIndex
,
11239 containerRect
= this.$element
[ 0 ].getBoundingClientRect();
11241 if ( !containerRect
|| ( !containerRect
.top
&& !containerRect
.bottom
) ) {
11242 // Can't get bounding rect, possibly not attached.
11246 function getRect( item
) {
11247 return item
.$element
[ 0 ].getBoundingClientRect();
11250 function isVisible( item
) {
11251 var rect
= getRect( item
);
11252 return rect
.bottom
> containerRect
.top
&& rect
.top
< containerRect
.bottom
;
11255 currentRect
= getRect( this.currentItem
);
11257 if ( currentRect
.bottom
< containerRect
.top
) {
11258 // Scrolled down past current item
11259 while ( ++newIndex
< len
) {
11260 if ( isVisible( this.items
[ newIndex
] ) ) {
11264 } else if ( currentRect
.top
> containerRect
.bottom
) {
11265 // Scrolled up past current item
11266 while ( --newIndex
>= 0 ) {
11267 if ( isVisible( this.items
[ newIndex
] ) ) {
11273 if ( newIndex
!== currentIndex
) {
11274 this.emit( 'visibleItemChange', this.items
[ newIndex
] );
11279 * Get the current panel.
11281 * @return {OO.ui.Layout|null}
11283 OO
.ui
.StackLayout
.prototype.getCurrentItem = function () {
11284 return this.currentItem
;
11288 * Unset the current item.
11291 * @param {OO.ui.StackLayout} layout
11294 OO
.ui
.StackLayout
.prototype.unsetCurrentItem = function () {
11295 var prevItem
= this.currentItem
;
11296 if ( prevItem
=== null ) {
11300 this.currentItem
= null;
11301 this.emit( 'set', null );
11305 * Add panel layouts to the stack layout.
11307 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
11308 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
11311 * @param {OO.ui.Layout[]} items Panels to add
11312 * @param {number} [index] Index of the insertion point
11315 OO
.ui
.StackLayout
.prototype.addItems = function ( items
, index
) {
11316 // Update the visibility
11317 this.updateHiddenState( items
, this.currentItem
);
11320 OO
.ui
.mixin
.GroupElement
.prototype.addItems
.call( this, items
, index
);
11322 if ( !this.currentItem
&& items
.length
) {
11323 this.setItem( items
[ 0 ] );
11330 * Remove the specified panels from the stack layout.
11332 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
11333 * you may wish to use the #clearItems method instead.
11335 * @param {OO.ui.Layout[]} items Panels to remove
11339 OO
.ui
.StackLayout
.prototype.removeItems = function ( items
) {
11341 OO
.ui
.mixin
.GroupElement
.prototype.removeItems
.call( this, items
);
11343 if ( items
.indexOf( this.currentItem
) !== -1 ) {
11344 if ( this.items
.length
) {
11345 this.setItem( this.items
[ 0 ] );
11347 this.unsetCurrentItem();
11355 * Clear all panels from the stack layout.
11357 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
11358 * a subset of panels, use the #removeItems method.
11363 OO
.ui
.StackLayout
.prototype.clearItems = function () {
11364 this.unsetCurrentItem();
11365 OO
.ui
.mixin
.GroupElement
.prototype.clearItems
.call( this );
11371 * Show the specified panel.
11373 * If another panel is currently displayed, it will be hidden.
11375 * @param {OO.ui.Layout} item Panel to show
11379 OO
.ui
.StackLayout
.prototype.setItem = function ( item
) {
11380 if ( item
!== this.currentItem
) {
11381 this.updateHiddenState( this.items
, item
);
11383 if ( this.items
.indexOf( item
) !== -1 ) {
11384 this.currentItem
= item
;
11385 this.emit( 'set', item
);
11387 this.unsetCurrentItem();
11395 * Update the visibility of all items in case of non-continuous view.
11397 * Ensure all items are hidden except for the selected one.
11398 * This method does nothing when the stack is continuous.
11401 * @param {OO.ui.Layout[]} items Item list iterate over
11402 * @param {OO.ui.Layout} [selectedItem] Selected item to show
11404 OO
.ui
.StackLayout
.prototype.updateHiddenState = function ( items
, selectedItem
) {
11407 if ( !this.continuous
) {
11408 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
11409 if ( !selectedItem
|| selectedItem
!== items
[ i
] ) {
11410 items
[ i
].$element
.addClass( 'oo-ui-element-hidden' );
11413 if ( selectedItem
) {
11414 selectedItem
.$element
.removeClass( 'oo-ui-element-hidden' );
11420 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
11421 * items), with small margins between them. Convenient when you need to put a number of block-level
11422 * widgets on a single line next to each other.
11424 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
11427 * // HorizontalLayout with a text input and a label
11428 * var layout = new OO.ui.HorizontalLayout( {
11430 * new OO.ui.LabelWidget( { label: 'Label' } ),
11431 * new OO.ui.TextInputWidget( { value: 'Text' } )
11434 * $( 'body' ).append( layout.$element );
11437 * @extends OO.ui.Layout
11438 * @mixins OO.ui.mixin.GroupElement
11441 * @param {Object} [config] Configuration options
11442 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
11444 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
11445 // Configuration initialization
11446 config
= config
|| {};
11448 // Parent constructor
11449 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
11451 // Mixin constructors
11452 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11455 this.$element
.addClass( 'oo-ui-horizontalLayout' );
11456 if ( Array
.isArray( config
.items
) ) {
11457 this.addItems( config
.items
);
11463 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
11464 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);
11467 * BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11468 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11469 * and {@link OO.ui.ListToolGroup ListToolGroup}). The {@link OO.ui.Tool tools} in a BarToolGroup are
11470 * displayed by icon in a single row. The title of the tool is displayed when users move the mouse over
11473 * BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar is
11477 * // Example of a BarToolGroup with two tools
11478 * var toolFactory = new OO.ui.ToolFactory();
11479 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11480 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11482 * // We will be placing status text in this element when tools are used
11483 * var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' );
11485 * // Define the tools that we're going to place in our toolbar
11487 * // Create a class inheriting from OO.ui.Tool
11488 * function ImageTool() {
11489 * ImageTool.parent.apply( this, arguments );
11491 * OO.inheritClass( ImageTool, OO.ui.Tool );
11492 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
11493 * // of 'icon' and 'title' (displayed icon and text).
11494 * ImageTool.static.name = 'image';
11495 * ImageTool.static.icon = 'image';
11496 * ImageTool.static.title = 'Insert image';
11497 * // Defines the action that will happen when this tool is selected (clicked).
11498 * ImageTool.prototype.onSelect = function () {
11499 * $area.text( 'Image tool clicked!' );
11500 * // Never display this tool as "active" (selected).
11501 * this.setActive( false );
11503 * // Make this tool available in our toolFactory and thus our toolbar
11504 * toolFactory.register( ImageTool );
11506 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
11507 * // little popup window (a PopupWidget).
11508 * function HelpTool( toolGroup, config ) {
11509 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11514 * this.popup.$body.append( '<p>I am helpful!</p>' );
11516 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11517 * HelpTool.static.name = 'help';
11518 * HelpTool.static.icon = 'help';
11519 * HelpTool.static.title = 'Help';
11520 * toolFactory.register( HelpTool );
11522 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11523 * // used once (but not all defined tools must be used).
11526 * // 'bar' tool groups display tools by icon only
11528 * include: [ 'image', 'help' ]
11532 * // Create some UI around the toolbar and place it in the document
11533 * var frame = new OO.ui.PanelLayout( {
11537 * var contentFrame = new OO.ui.PanelLayout( {
11541 * frame.$element.append(
11542 * toolbar.$element,
11543 * contentFrame.$element.append( $area )
11545 * $( 'body' ).append( frame.$element );
11547 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11549 * toolbar.initialize();
11551 * For more information about how to add tools to a bar tool group, please see {@link OO.ui.ToolGroup toolgroup}.
11552 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11554 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11557 * @extends OO.ui.ToolGroup
11560 * @param {OO.ui.Toolbar} toolbar
11561 * @param {Object} [config] Configuration options
11563 OO
.ui
.BarToolGroup
= function OoUiBarToolGroup( toolbar
, config
) {
11564 // Allow passing positional parameters inside the config object
11565 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11567 toolbar
= config
.toolbar
;
11570 // Parent constructor
11571 OO
.ui
.BarToolGroup
.parent
.call( this, toolbar
, config
);
11574 this.$element
.addClass( 'oo-ui-barToolGroup' );
11579 OO
.inheritClass( OO
.ui
.BarToolGroup
, OO
.ui
.ToolGroup
);
11581 /* Static Properties */
11583 OO
.ui
.BarToolGroup
.static.titleTooltips
= true;
11585 OO
.ui
.BarToolGroup
.static.accelTooltips
= true;
11587 OO
.ui
.BarToolGroup
.static.name
= 'bar';
11590 * PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup}
11591 * and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup--an overlaid menu or list of tools with an
11592 * optional icon and label. This class can be used for other base classes that also use this functionality.
11596 * @extends OO.ui.ToolGroup
11597 * @mixins OO.ui.mixin.IconElement
11598 * @mixins OO.ui.mixin.IndicatorElement
11599 * @mixins OO.ui.mixin.LabelElement
11600 * @mixins OO.ui.mixin.TitledElement
11601 * @mixins OO.ui.mixin.ClippableElement
11602 * @mixins OO.ui.mixin.TabIndexedElement
11605 * @param {OO.ui.Toolbar} toolbar
11606 * @param {Object} [config] Configuration options
11607 * @cfg {string} [header] Text to display at the top of the popup
11609 OO
.ui
.PopupToolGroup
= function OoUiPopupToolGroup( toolbar
, config
) {
11610 // Allow passing positional parameters inside the config object
11611 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11613 toolbar
= config
.toolbar
;
11616 // Configuration initialization
11617 config
= config
|| {};
11619 // Parent constructor
11620 OO
.ui
.PopupToolGroup
.parent
.call( this, toolbar
, config
);
11623 this.active
= false;
11624 this.dragging
= false;
11625 this.onBlurHandler
= this.onBlur
.bind( this );
11626 this.$handle
= $( '<span>' );
11628 // Mixin constructors
11629 OO
.ui
.mixin
.IconElement
.call( this, config
);
11630 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
11631 OO
.ui
.mixin
.LabelElement
.call( this, config
);
11632 OO
.ui
.mixin
.TitledElement
.call( this, config
);
11633 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
11634 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
11638 keydown
: this.onHandleMouseKeyDown
.bind( this ),
11639 keyup
: this.onHandleMouseKeyUp
.bind( this ),
11640 mousedown
: this.onHandleMouseKeyDown
.bind( this ),
11641 mouseup
: this.onHandleMouseKeyUp
.bind( this )
11646 .addClass( 'oo-ui-popupToolGroup-handle' )
11647 .append( this.$icon
, this.$label
, this.$indicator
);
11648 // If the pop-up should have a header, add it to the top of the toolGroup.
11649 // Note: If this feature is useful for other widgets, we could abstract it into an
11650 // OO.ui.HeaderedElement mixin constructor.
11651 if ( config
.header
!== undefined ) {
11653 .prepend( $( '<span>' )
11654 .addClass( 'oo-ui-popupToolGroup-header' )
11655 .text( config
.header
)
11659 .addClass( 'oo-ui-popupToolGroup' )
11660 .prepend( this.$handle
);
11665 OO
.inheritClass( OO
.ui
.PopupToolGroup
, OO
.ui
.ToolGroup
);
11666 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.IconElement
);
11667 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.IndicatorElement
);
11668 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.LabelElement
);
11669 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.TitledElement
);
11670 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.ClippableElement
);
11671 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.TabIndexedElement
);
11678 OO
.ui
.PopupToolGroup
.prototype.setDisabled = function () {
11680 OO
.ui
.PopupToolGroup
.parent
.prototype.setDisabled
.apply( this, arguments
);
11682 if ( this.isDisabled() && this.isElementAttached() ) {
11683 this.setActive( false );
11688 * Handle focus being lost.
11690 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
11693 * @param {jQuery.Event} e Mouse up or key up event
11695 OO
.ui
.PopupToolGroup
.prototype.onBlur = function ( e
) {
11696 // Only deactivate when clicking outside the dropdown element
11697 if ( $( e
.target
).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element
[ 0 ] ) {
11698 this.setActive( false );
11705 OO
.ui
.PopupToolGroup
.prototype.onMouseKeyUp = function ( e
) {
11706 // Only close toolgroup when a tool was actually selected
11708 !this.isDisabled() && this.pressed
&& this.pressed
=== this.getTargetTool( e
) &&
11709 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11711 this.setActive( false );
11713 return OO
.ui
.PopupToolGroup
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11717 * Handle mouse up and key up events.
11720 * @param {jQuery.Event} e Mouse up or key up event
11722 OO
.ui
.PopupToolGroup
.prototype.onHandleMouseKeyUp = function ( e
) {
11724 !this.isDisabled() &&
11725 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11732 * Handle mouse down and key down events.
11735 * @param {jQuery.Event} e Mouse down or key down event
11737 OO
.ui
.PopupToolGroup
.prototype.onHandleMouseKeyDown = function ( e
) {
11739 !this.isDisabled() &&
11740 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11742 this.setActive( !this.active
);
11748 * Switch into 'active' mode.
11750 * When active, the popup is visible. A mouseup event anywhere in the document will trigger
11753 OO
.ui
.PopupToolGroup
.prototype.setActive = function ( value
) {
11754 var containerWidth
, containerLeft
;
11756 if ( this.active
!== value
) {
11757 this.active
= value
;
11759 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler
);
11760 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler
);
11762 this.$clippable
.css( 'left', '' );
11763 // Try anchoring the popup to the left first
11764 this.$element
.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
11765 this.toggleClipping( true );
11766 if ( this.isClippedHorizontally() ) {
11767 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
11768 this.toggleClipping( false );
11770 .removeClass( 'oo-ui-popupToolGroup-left' )
11771 .addClass( 'oo-ui-popupToolGroup-right' );
11772 this.toggleClipping( true );
11774 if ( this.isClippedHorizontally() ) {
11775 // Anchoring to the right also caused the popup to clip, so just make it fill the container
11776 containerWidth
= this.$clippableScrollableContainer
.width();
11777 containerLeft
= this.$clippableScrollableContainer
.offset().left
;
11779 this.toggleClipping( false );
11780 this.$element
.removeClass( 'oo-ui-popupToolGroup-right' );
11782 this.$clippable
.css( {
11783 left
: -( this.$element
.offset().left
- containerLeft
),
11784 width
: containerWidth
11788 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler
);
11789 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler
);
11790 this.$element
.removeClass(
11791 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
11793 this.toggleClipping( false );
11799 * ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11800 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11801 * and {@link OO.ui.BarToolGroup BarToolGroup}). The {@link OO.ui.Tool tools} in a ListToolGroup are displayed
11802 * by label in a dropdown menu. The title of the tool is used as the label text. The menu itself can be configured
11803 * with a label, icon, indicator, header, and title.
11805 * ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a ‘More’ option that
11806 * users can select to see the full list of tools. If a collapsed toolgroup is expanded, a ‘Fewer’ option permits
11807 * users to collapse the list again.
11809 * ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the toolbar is set up. The factory
11810 * requires the ListToolGroup's symbolic name, 'list', which is specified along with the other configurations. For more
11811 * information about how to add tools to a ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11814 * // Example of a ListToolGroup
11815 * var toolFactory = new OO.ui.ToolFactory();
11816 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11817 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11819 * // Configure and register two tools
11820 * function SettingsTool() {
11821 * SettingsTool.parent.apply( this, arguments );
11823 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11824 * SettingsTool.static.name = 'settings';
11825 * SettingsTool.static.icon = 'settings';
11826 * SettingsTool.static.title = 'Change settings';
11827 * SettingsTool.prototype.onSelect = function () {
11828 * this.setActive( false );
11830 * toolFactory.register( SettingsTool );
11831 * // Register two more tools, nothing interesting here
11832 * function StuffTool() {
11833 * StuffTool.parent.apply( this, arguments );
11835 * OO.inheritClass( StuffTool, OO.ui.Tool );
11836 * StuffTool.static.name = 'stuff';
11837 * StuffTool.static.icon = 'ellipsis';
11838 * StuffTool.static.title = 'Change the world';
11839 * StuffTool.prototype.onSelect = function () {
11840 * this.setActive( false );
11842 * toolFactory.register( StuffTool );
11845 * // Configurations for list toolgroup.
11847 * label: 'ListToolGroup',
11848 * indicator: 'down',
11850 * title: 'This is the title, displayed when user moves the mouse over the list toolgroup',
11851 * header: 'This is the header',
11852 * include: [ 'settings', 'stuff' ],
11853 * allowCollapse: ['stuff']
11857 * // Create some UI around the toolbar and place it in the document
11858 * var frame = new OO.ui.PanelLayout( {
11862 * frame.$element.append(
11865 * $( 'body' ).append( frame.$element );
11866 * // Build the toolbar. This must be done after the toolbar has been appended to the document.
11867 * toolbar.initialize();
11869 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11871 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11874 * @extends OO.ui.PopupToolGroup
11877 * @param {OO.ui.Toolbar} toolbar
11878 * @param {Object} [config] Configuration options
11879 * @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible tools
11880 * will only be displayed if users click the ‘More’ option displayed at the bottom of the list. If
11881 * the list is expanded, a ‘Fewer’ option permits users to collapse the list again. Any tools that
11882 * are included in the toolgroup, but are not designated as collapsible, will always be displayed.
11883 * To open a collapsible list in its expanded state, set #expanded to 'true'.
11884 * @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as collapsible.
11885 * Unless #expanded is set to true, the collapsible tools will be collapsed when the list is first opened.
11886 * @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools have
11887 * been designated as collapsible. When expanded is set to true, all tools in the group will be displayed
11888 * when the list is first opened. Users can collapse the list with a ‘Fewer’ option at the bottom.
11890 OO
.ui
.ListToolGroup
= function OoUiListToolGroup( toolbar
, config
) {
11891 // Allow passing positional parameters inside the config object
11892 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11894 toolbar
= config
.toolbar
;
11897 // Configuration initialization
11898 config
= config
|| {};
11900 // Properties (must be set before parent constructor, which calls #populate)
11901 this.allowCollapse
= config
.allowCollapse
;
11902 this.forceExpand
= config
.forceExpand
;
11903 this.expanded
= config
.expanded
!== undefined ? config
.expanded
: false;
11904 this.collapsibleTools
= [];
11906 // Parent constructor
11907 OO
.ui
.ListToolGroup
.parent
.call( this, toolbar
, config
);
11910 this.$element
.addClass( 'oo-ui-listToolGroup' );
11915 OO
.inheritClass( OO
.ui
.ListToolGroup
, OO
.ui
.PopupToolGroup
);
11917 /* Static Properties */
11919 OO
.ui
.ListToolGroup
.static.name
= 'list';
11926 OO
.ui
.ListToolGroup
.prototype.populate = function () {
11927 var i
, len
, allowCollapse
= [];
11929 OO
.ui
.ListToolGroup
.parent
.prototype.populate
.call( this );
11931 // Update the list of collapsible tools
11932 if ( this.allowCollapse
!== undefined ) {
11933 allowCollapse
= this.allowCollapse
;
11934 } else if ( this.forceExpand
!== undefined ) {
11935 allowCollapse
= OO
.simpleArrayDifference( Object
.keys( this.tools
), this.forceExpand
);
11938 this.collapsibleTools
= [];
11939 for ( i
= 0, len
= allowCollapse
.length
; i
< len
; i
++ ) {
11940 if ( this.tools
[ allowCollapse
[ i
] ] !== undefined ) {
11941 this.collapsibleTools
.push( this.tools
[ allowCollapse
[ i
] ] );
11945 // Keep at the end, even when tools are added
11946 this.$group
.append( this.getExpandCollapseTool().$element
);
11948 this.getExpandCollapseTool().toggle( this.collapsibleTools
.length
!== 0 );
11949 this.updateCollapsibleState();
11952 OO
.ui
.ListToolGroup
.prototype.getExpandCollapseTool = function () {
11953 var ExpandCollapseTool
;
11954 if ( this.expandCollapseTool
=== undefined ) {
11955 ExpandCollapseTool = function () {
11956 ExpandCollapseTool
.parent
.apply( this, arguments
);
11959 OO
.inheritClass( ExpandCollapseTool
, OO
.ui
.Tool
);
11961 ExpandCollapseTool
.prototype.onSelect = function () {
11962 this.toolGroup
.expanded
= !this.toolGroup
.expanded
;
11963 this.toolGroup
.updateCollapsibleState();
11964 this.setActive( false );
11966 ExpandCollapseTool
.prototype.onUpdateState = function () {
11967 // Do nothing. Tool interface requires an implementation of this function.
11970 ExpandCollapseTool
.static.name
= 'more-fewer';
11972 this.expandCollapseTool
= new ExpandCollapseTool( this );
11974 return this.expandCollapseTool
;
11980 OO
.ui
.ListToolGroup
.prototype.onMouseKeyUp = function ( e
) {
11981 // Do not close the popup when the user wants to show more/fewer tools
11983 $( e
.target
).closest( '.oo-ui-tool-name-more-fewer' ).length
&&
11984 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11986 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
11987 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
11988 return OO
.ui
.ListToolGroup
.parent
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11990 return OO
.ui
.ListToolGroup
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11994 OO
.ui
.ListToolGroup
.prototype.updateCollapsibleState = function () {
11997 this.getExpandCollapseTool()
11998 .setIcon( this.expanded
? 'collapse' : 'expand' )
11999 .setTitle( OO
.ui
.msg( this.expanded
? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
12001 for ( i
= 0, len
= this.collapsibleTools
.length
; i
< len
; i
++ ) {
12002 this.collapsibleTools
[ i
].toggle( this.expanded
);
12007 * MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
12008 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.BarToolGroup BarToolGroup}
12009 * and {@link OO.ui.ListToolGroup ListToolGroup}). MenuToolGroups contain selectable {@link OO.ui.Tool tools},
12010 * which are displayed by label in a dropdown menu. The tool's title is used as the label text, and the
12011 * menu label is updated to reflect which tool or tools are currently selected. If no tools are selected,
12012 * the menu label is empty. The menu can be configured with an indicator, icon, title, and/or header.
12014 * MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar
12015 * is set up. Note that all tools must define an {@link OO.ui.Tool#onUpdateState onUpdateState} method if
12016 * a MenuToolGroup is used.
12019 * // Example of a MenuToolGroup
12020 * var toolFactory = new OO.ui.ToolFactory();
12021 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
12022 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
12024 * // We will be placing status text in this element when tools are used
12025 * var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the dropdown menu.' );
12027 * // Define the tools that we're going to place in our toolbar
12029 * function SettingsTool() {
12030 * SettingsTool.parent.apply( this, arguments );
12031 * this.reallyActive = false;
12033 * OO.inheritClass( SettingsTool, OO.ui.Tool );
12034 * SettingsTool.static.name = 'settings';
12035 * SettingsTool.static.icon = 'settings';
12036 * SettingsTool.static.title = 'Change settings';
12037 * SettingsTool.prototype.onSelect = function () {
12038 * $area.text( 'Settings tool clicked!' );
12039 * // Toggle the active state on each click
12040 * this.reallyActive = !this.reallyActive;
12041 * this.setActive( this.reallyActive );
12042 * // To update the menu label
12043 * this.toolbar.emit( 'updateState' );
12045 * SettingsTool.prototype.onUpdateState = function () {
12047 * toolFactory.register( SettingsTool );
12049 * function StuffTool() {
12050 * StuffTool.parent.apply( this, arguments );
12051 * this.reallyActive = false;
12053 * OO.inheritClass( StuffTool, OO.ui.Tool );
12054 * StuffTool.static.name = 'stuff';
12055 * StuffTool.static.icon = 'ellipsis';
12056 * StuffTool.static.title = 'More stuff';
12057 * StuffTool.prototype.onSelect = function () {
12058 * $area.text( 'More stuff tool clicked!' );
12059 * // Toggle the active state on each click
12060 * this.reallyActive = !this.reallyActive;
12061 * this.setActive( this.reallyActive );
12062 * // To update the menu label
12063 * this.toolbar.emit( 'updateState' );
12065 * StuffTool.prototype.onUpdateState = function () {
12067 * toolFactory.register( StuffTool );
12069 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
12070 * // used once (but not all defined tools must be used).
12074 * header: 'This is the (optional) header',
12075 * title: 'This is the (optional) title',
12076 * indicator: 'down',
12077 * include: [ 'settings', 'stuff' ]
12081 * // Create some UI around the toolbar and place it in the document
12082 * var frame = new OO.ui.PanelLayout( {
12086 * var contentFrame = new OO.ui.PanelLayout( {
12090 * frame.$element.append(
12091 * toolbar.$element,
12092 * contentFrame.$element.append( $area )
12094 * $( 'body' ).append( frame.$element );
12096 * // Here is where the toolbar is actually built. This must be done after inserting it into the
12098 * toolbar.initialize();
12099 * toolbar.emit( 'updateState' );
12101 * For more information about how to add tools to a MenuToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
12102 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki] [1].
12104 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
12107 * @extends OO.ui.PopupToolGroup
12110 * @param {OO.ui.Toolbar} toolbar
12111 * @param {Object} [config] Configuration options
12113 OO
.ui
.MenuToolGroup
= function OoUiMenuToolGroup( toolbar
, config
) {
12114 // Allow passing positional parameters inside the config object
12115 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
12117 toolbar
= config
.toolbar
;
12120 // Configuration initialization
12121 config
= config
|| {};
12123 // Parent constructor
12124 OO
.ui
.MenuToolGroup
.parent
.call( this, toolbar
, config
);
12127 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
12130 this.$element
.addClass( 'oo-ui-menuToolGroup' );
12135 OO
.inheritClass( OO
.ui
.MenuToolGroup
, OO
.ui
.PopupToolGroup
);
12137 /* Static Properties */
12139 OO
.ui
.MenuToolGroup
.static.name
= 'menu';
12144 * Handle the toolbar state being updated.
12146 * When the state changes, the title of each active item in the menu will be joined together and
12147 * used as a label for the group. The label will be empty if none of the items are active.
12151 OO
.ui
.MenuToolGroup
.prototype.onUpdateState = function () {
12155 for ( name
in this.tools
) {
12156 if ( this.tools
[ name
].isActive() ) {
12157 labelTexts
.push( this.tools
[ name
].getTitle() );
12161 this.setLabel( labelTexts
.join( ', ' ) || ' ' );
12165 * Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. Each popup tool is configured
12166 * 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
12167 * an #onSelect or #onUpdateState method, as these methods have been implemented already.
12169 * // Example of a popup tool. When selected, a popup tool displays
12170 * // a popup window.
12171 * function HelpTool( toolGroup, config ) {
12172 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
12177 * this.popup.$body.append( '<p>I am helpful!</p>' );
12179 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
12180 * HelpTool.static.name = 'help';
12181 * HelpTool.static.icon = 'help';
12182 * HelpTool.static.title = 'Help';
12183 * toolFactory.register( HelpTool );
12185 * For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. For more information about
12186 * toolbars in genreral, please see the [OOjs UI documentation on MediaWiki][1].
12188 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
12192 * @extends OO.ui.Tool
12193 * @mixins OO.ui.mixin.PopupElement
12196 * @param {OO.ui.ToolGroup} toolGroup
12197 * @param {Object} [config] Configuration options
12199 OO
.ui
.PopupTool
= function OoUiPopupTool( toolGroup
, config
) {
12200 // Allow passing positional parameters inside the config object
12201 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
12202 config
= toolGroup
;
12203 toolGroup
= config
.toolGroup
;
12206 // Parent constructor
12207 OO
.ui
.PopupTool
.parent
.call( this, toolGroup
, config
);
12209 // Mixin constructors
12210 OO
.ui
.mixin
.PopupElement
.call( this, config
);
12214 .addClass( 'oo-ui-popupTool' )
12215 .append( this.popup
.$element
);
12220 OO
.inheritClass( OO
.ui
.PopupTool
, OO
.ui
.Tool
);
12221 OO
.mixinClass( OO
.ui
.PopupTool
, OO
.ui
.mixin
.PopupElement
);
12226 * Handle the tool being selected.
12230 OO
.ui
.PopupTool
.prototype.onSelect = function () {
12231 if ( !this.isDisabled() ) {
12232 this.popup
.toggle();
12234 this.setActive( false );
12239 * Handle the toolbar state being updated.
12243 OO
.ui
.PopupTool
.prototype.onUpdateState = function () {
12244 this.setActive( false );
12248 * A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools}
12249 * and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used
12250 * inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from
12251 * the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list}
12252 * when the ToolGroupTool is selected.
12254 * // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', defined elsewhere.
12256 * function SettingsTool() {
12257 * SettingsTool.parent.apply( this, arguments );
12259 * OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool );
12260 * SettingsTool.static.name = 'settings';
12261 * SettingsTool.static.title = 'Change settings';
12262 * SettingsTool.static.groupConfig = {
12263 * icon: 'settings',
12264 * label: 'ToolGroupTool',
12265 * include: [ 'setting1', 'setting2' ]
12267 * toolFactory.register( SettingsTool );
12269 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
12271 * Please note that this implementation is subject to change per [T74159] [2].
12273 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars#ToolGroupTool
12274 * [2]: https://phabricator.wikimedia.org/T74159
12278 * @extends OO.ui.Tool
12281 * @param {OO.ui.ToolGroup} toolGroup
12282 * @param {Object} [config] Configuration options
12284 OO
.ui
.ToolGroupTool
= function OoUiToolGroupTool( toolGroup
, config
) {
12285 // Allow passing positional parameters inside the config object
12286 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
12287 config
= toolGroup
;
12288 toolGroup
= config
.toolGroup
;
12291 // Parent constructor
12292 OO
.ui
.ToolGroupTool
.parent
.call( this, toolGroup
, config
);
12295 this.innerToolGroup
= this.createGroup( this.constructor.static.groupConfig
);
12298 this.innerToolGroup
.connect( this, { disable
: 'onToolGroupDisable' } );
12301 this.$link
.remove();
12303 .addClass( 'oo-ui-toolGroupTool' )
12304 .append( this.innerToolGroup
.$element
);
12309 OO
.inheritClass( OO
.ui
.ToolGroupTool
, OO
.ui
.Tool
);
12311 /* Static Properties */
12314 * Toolgroup configuration.
12316 * The toolgroup configuration consists of the tools to include, as well as an icon and label
12317 * to use for the bar item. Tools can be included by symbolic name, group, or with the
12318 * wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information.
12320 * @property {Object.<string,Array>}
12322 OO
.ui
.ToolGroupTool
.static.groupConfig
= {};
12327 * Handle the tool being selected.
12331 OO
.ui
.ToolGroupTool
.prototype.onSelect = function () {
12332 this.innerToolGroup
.setActive( !this.innerToolGroup
.active
);
12337 * Synchronize disabledness state of the tool with the inner toolgroup.
12340 * @param {boolean} disabled Element is disabled
12342 OO
.ui
.ToolGroupTool
.prototype.onToolGroupDisable = function ( disabled
) {
12343 this.setDisabled( disabled
);
12347 * Handle the toolbar state being updated.
12351 OO
.ui
.ToolGroupTool
.prototype.onUpdateState = function () {
12352 this.setActive( false );
12356 * Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration.
12358 * @param {Object.<string,Array>} group Toolgroup configuration. Please see {@link OO.ui.ToolGroup toolgroup} for
12359 * more information.
12360 * @return {OO.ui.ListToolGroup}
12362 OO
.ui
.ToolGroupTool
.prototype.createGroup = function ( group
) {
12363 if ( group
.include
=== '*' ) {
12364 // Apply defaults to catch-all groups
12365 if ( group
.label
=== undefined ) {
12366 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
12370 return this.toolbar
.getToolGroupFactory().create( 'list', this.toolbar
, group
);
12374 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
12376 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
12381 * @extends OO.ui.mixin.GroupElement
12384 * @param {Object} [config] Configuration options
12386 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
12387 // Parent constructor
12388 OO
.ui
.mixin
.GroupWidget
.parent
.call( this, config
);
12393 OO
.inheritClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
12398 * Set the disabled state of the widget.
12400 * This will also update the disabled state of child widgets.
12402 * @param {boolean} disabled Disable widget
12405 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
12409 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
12410 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
12412 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
12413 if ( this.items
) {
12414 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
12415 this.items
[ i
].updateDisabled();
12423 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
12425 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
12426 * allows bidirectional communication.
12428 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
12436 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
12443 * Check if widget is disabled.
12445 * Checks parent if present, making disabled state inheritable.
12447 * @return {boolean} Widget is disabled
12449 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
12450 return this.disabled
||
12451 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
12455 * Set group element is in.
12457 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
12460 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
12462 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
12463 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
12465 // Initialize item disabled states
12466 this.updateDisabled();
12472 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
12473 * Controls include moving items up and down, removing items, and adding different kinds of items.
12475 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
12478 * @extends OO.ui.Widget
12479 * @mixins OO.ui.mixin.GroupElement
12480 * @mixins OO.ui.mixin.IconElement
12483 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
12484 * @param {Object} [config] Configuration options
12485 * @cfg {Object} [abilities] List of abilties
12486 * @cfg {boolean} [abilities.move=true] Allow moving movable items
12487 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
12489 OO
.ui
.OutlineControlsWidget
= function OoUiOutlineControlsWidget( outline
, config
) {
12490 // Allow passing positional parameters inside the config object
12491 if ( OO
.isPlainObject( outline
) && config
=== undefined ) {
12493 outline
= config
.outline
;
12496 // Configuration initialization
12497 config
= $.extend( { icon
: 'add' }, config
);
12499 // Parent constructor
12500 OO
.ui
.OutlineControlsWidget
.parent
.call( this, config
);
12502 // Mixin constructors
12503 OO
.ui
.mixin
.GroupElement
.call( this, config
);
12504 OO
.ui
.mixin
.IconElement
.call( this, config
);
12507 this.outline
= outline
;
12508 this.$movers
= $( '<div>' );
12509 this.upButton
= new OO
.ui
.ButtonWidget( {
12512 title
: OO
.ui
.msg( 'ooui-outline-control-move-up' )
12514 this.downButton
= new OO
.ui
.ButtonWidget( {
12517 title
: OO
.ui
.msg( 'ooui-outline-control-move-down' )
12519 this.removeButton
= new OO
.ui
.ButtonWidget( {
12522 title
: OO
.ui
.msg( 'ooui-outline-control-remove' )
12524 this.abilities
= { move: true, remove
: true };
12527 outline
.connect( this, {
12528 select
: 'onOutlineChange',
12529 add
: 'onOutlineChange',
12530 remove
: 'onOutlineChange'
12532 this.upButton
.connect( this, { click
: [ 'emit', 'move', -1 ] } );
12533 this.downButton
.connect( this, { click
: [ 'emit', 'move', 1 ] } );
12534 this.removeButton
.connect( this, { click
: [ 'emit', 'remove' ] } );
12537 this.$element
.addClass( 'oo-ui-outlineControlsWidget' );
12538 this.$group
.addClass( 'oo-ui-outlineControlsWidget-items' );
12540 .addClass( 'oo-ui-outlineControlsWidget-movers' )
12541 .append( this.removeButton
.$element
, this.upButton
.$element
, this.downButton
.$element
);
12542 this.$element
.append( this.$icon
, this.$group
, this.$movers
);
12543 this.setAbilities( config
.abilities
|| {} );
12548 OO
.inheritClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.Widget
);
12549 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.mixin
.GroupElement
);
12550 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.mixin
.IconElement
);
12556 * @param {number} places Number of places to move
12568 * @param {Object} abilities List of abilties
12569 * @param {boolean} [abilities.move] Allow moving movable items
12570 * @param {boolean} [abilities.remove] Allow removing removable items
12572 OO
.ui
.OutlineControlsWidget
.prototype.setAbilities = function ( abilities
) {
12575 for ( ability
in this.abilities
) {
12576 if ( abilities
[ ability
] !== undefined ) {
12577 this.abilities
[ ability
] = !!abilities
[ ability
];
12581 this.onOutlineChange();
12586 * Handle outline change events.
12588 OO
.ui
.OutlineControlsWidget
.prototype.onOutlineChange = function () {
12589 var i
, len
, firstMovable
, lastMovable
,
12590 items
= this.outline
.getItems(),
12591 selectedItem
= this.outline
.getSelectedItem(),
12592 movable
= this.abilities
.move && selectedItem
&& selectedItem
.isMovable(),
12593 removable
= this.abilities
.remove
&& selectedItem
&& selectedItem
.isRemovable();
12597 len
= items
.length
;
12598 while ( ++i
< len
) {
12599 if ( items
[ i
].isMovable() ) {
12600 firstMovable
= items
[ i
];
12606 if ( items
[ i
].isMovable() ) {
12607 lastMovable
= items
[ i
];
12612 this.upButton
.setDisabled( !movable
|| selectedItem
=== firstMovable
);
12613 this.downButton
.setDisabled( !movable
|| selectedItem
=== lastMovable
);
12614 this.removeButton
.setDisabled( !removable
);
12618 * ToggleWidget implements basic behavior of widgets with an on/off state.
12619 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
12623 * @extends OO.ui.Widget
12626 * @param {Object} [config] Configuration options
12627 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
12628 * By default, the toggle is in the 'off' state.
12630 OO
.ui
.ToggleWidget
= function OoUiToggleWidget( config
) {
12631 // Configuration initialization
12632 config
= config
|| {};
12634 // Parent constructor
12635 OO
.ui
.ToggleWidget
.parent
.call( this, config
);
12641 this.$element
.addClass( 'oo-ui-toggleWidget' );
12642 this.setValue( !!config
.value
);
12647 OO
.inheritClass( OO
.ui
.ToggleWidget
, OO
.ui
.Widget
);
12654 * A change event is emitted when the on/off state of the toggle changes.
12656 * @param {boolean} value Value representing the new state of the toggle
12662 * Get the value representing the toggle’s state.
12664 * @return {boolean} The on/off state of the toggle
12666 OO
.ui
.ToggleWidget
.prototype.getValue = function () {
12671 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
12673 * @param {boolean} value The state of the toggle
12677 OO
.ui
.ToggleWidget
.prototype.setValue = function ( value
) {
12679 if ( this.value
!== value
) {
12680 this.value
= value
;
12681 this.emit( 'change', value
);
12682 this.$element
.toggleClass( 'oo-ui-toggleWidget-on', value
);
12683 this.$element
.toggleClass( 'oo-ui-toggleWidget-off', !value
);
12684 this.$element
.attr( 'aria-checked', value
.toString() );
12690 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
12691 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
12692 * removed, and cleared from the group.
12695 * // Example: A ButtonGroupWidget with two buttons
12696 * var button1 = new OO.ui.PopupButtonWidget( {
12697 * label: 'Select a category',
12700 * $content: $( '<p>List of categories...</p>' ),
12705 * var button2 = new OO.ui.ButtonWidget( {
12706 * label: 'Add item'
12708 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
12709 * items: [button1, button2]
12711 * $( 'body' ).append( buttonGroup.$element );
12714 * @extends OO.ui.Widget
12715 * @mixins OO.ui.mixin.GroupElement
12718 * @param {Object} [config] Configuration options
12719 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
12721 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
12722 // Configuration initialization
12723 config
= config
|| {};
12725 // Parent constructor
12726 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
12728 // Mixin constructors
12729 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
12732 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
12733 if ( Array
.isArray( config
.items
) ) {
12734 this.addItems( config
.items
);
12740 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
12741 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
12744 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
12745 * feels, and functionality can be customized via the class’s configuration options
12746 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12749 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
12752 * // A button widget
12753 * var button = new OO.ui.ButtonWidget( {
12754 * label: 'Button with Icon',
12756 * iconTitle: 'Remove'
12758 * $( 'body' ).append( button.$element );
12760 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
12763 * @extends OO.ui.Widget
12764 * @mixins OO.ui.mixin.ButtonElement
12765 * @mixins OO.ui.mixin.IconElement
12766 * @mixins OO.ui.mixin.IndicatorElement
12767 * @mixins OO.ui.mixin.LabelElement
12768 * @mixins OO.ui.mixin.TitledElement
12769 * @mixins OO.ui.mixin.FlaggedElement
12770 * @mixins OO.ui.mixin.TabIndexedElement
12771 * @mixins OO.ui.mixin.AccessKeyedElement
12774 * @param {Object} [config] Configuration options
12775 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
12776 * @cfg {string} [target] The frame or window in which to open the hyperlink.
12777 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
12779 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
12780 // Configuration initialization
12781 config
= config
|| {};
12783 // Parent constructor
12784 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
12786 // Mixin constructors
12787 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
12788 OO
.ui
.mixin
.IconElement
.call( this, config
);
12789 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
12790 OO
.ui
.mixin
.LabelElement
.call( this, config
);
12791 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
12792 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
12793 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
12794 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$button
} ) );
12798 this.target
= null;
12799 this.noFollow
= false;
12802 this.connect( this, { disable
: 'onDisable' } );
12805 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
12807 .addClass( 'oo-ui-buttonWidget' )
12808 .append( this.$button
);
12809 this.setHref( config
.href
);
12810 this.setTarget( config
.target
);
12811 this.setNoFollow( config
.noFollow
);
12816 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
12817 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
12818 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
12819 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
12820 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
12821 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
12822 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
12823 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
12824 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
12831 OO
.ui
.ButtonWidget
.prototype.onMouseDown = function ( e
) {
12832 if ( !this.isDisabled() ) {
12833 // Remove the tab-index while the button is down to prevent the button from stealing focus
12834 this.$button
.removeAttr( 'tabindex' );
12837 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown
.call( this, e
);
12843 OO
.ui
.ButtonWidget
.prototype.onMouseUp = function ( e
) {
12844 if ( !this.isDisabled() ) {
12845 // Restore the tab-index after the button is up to restore the button's accessibility
12846 this.$button
.attr( 'tabindex', this.tabIndex
);
12849 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp
.call( this, e
);
12853 * Get hyperlink location.
12855 * @return {string} Hyperlink location
12857 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
12862 * Get hyperlink target.
12864 * @return {string} Hyperlink target
12866 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
12867 return this.target
;
12871 * Get search engine traversal hint.
12873 * @return {boolean} Whether search engines should avoid traversing this hyperlink
12875 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
12876 return this.noFollow
;
12880 * Set hyperlink location.
12882 * @param {string|null} href Hyperlink location, null to remove
12884 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
12885 href
= typeof href
=== 'string' ? href
: null;
12886 if ( href
!== null ) {
12887 if ( !OO
.ui
.isSafeUrl( href
) ) {
12888 throw new Error( 'Potentially unsafe href provided: ' + href
);
12893 if ( href
!== this.href
) {
12902 * Update the `href` attribute, in case of changes to href or
12908 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
12909 if ( this.href
!== null && !this.isDisabled() ) {
12910 this.$button
.attr( 'href', this.href
);
12912 this.$button
.removeAttr( 'href' );
12919 * Handle disable events.
12922 * @param {boolean} disabled Element is disabled
12924 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
12929 * Set hyperlink target.
12931 * @param {string|null} target Hyperlink target, null to remove
12933 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
12934 target
= typeof target
=== 'string' ? target
: null;
12936 if ( target
!== this.target
) {
12937 this.target
= target
;
12938 if ( target
!== null ) {
12939 this.$button
.attr( 'target', target
);
12941 this.$button
.removeAttr( 'target' );
12949 * Set search engine traversal hint.
12951 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
12953 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
12954 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
12956 if ( noFollow
!== this.noFollow
) {
12957 this.noFollow
= noFollow
;
12959 this.$button
.attr( 'rel', 'nofollow' );
12961 this.$button
.removeAttr( 'rel' );
12969 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
12970 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
12973 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
12974 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12977 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
12980 * @extends OO.ui.ButtonWidget
12981 * @mixins OO.ui.mixin.PendingElement
12984 * @param {Object} [config] Configuration options
12985 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12986 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
12987 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
12988 * for more information about setting modes.
12989 * @cfg {boolean} [framed=false] Render the action button with a frame
12991 OO
.ui
.ActionWidget
= function OoUiActionWidget( config
) {
12992 // Configuration initialization
12993 config
= $.extend( { framed
: false }, config
);
12995 // Parent constructor
12996 OO
.ui
.ActionWidget
.parent
.call( this, config
);
12998 // Mixin constructors
12999 OO
.ui
.mixin
.PendingElement
.call( this, config
);
13002 this.action
= config
.action
|| '';
13003 this.modes
= config
.modes
|| [];
13008 this.$element
.addClass( 'oo-ui-actionWidget' );
13013 OO
.inheritClass( OO
.ui
.ActionWidget
, OO
.ui
.ButtonWidget
);
13014 OO
.mixinClass( OO
.ui
.ActionWidget
, OO
.ui
.mixin
.PendingElement
);
13019 * A resize event is emitted when the size of the widget changes.
13027 * Check if the action is configured to be available in the specified `mode`.
13029 * @param {string} mode Name of mode
13030 * @return {boolean} The action is configured with the mode
13032 OO
.ui
.ActionWidget
.prototype.hasMode = function ( mode
) {
13033 return this.modes
.indexOf( mode
) !== -1;
13037 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
13041 OO
.ui
.ActionWidget
.prototype.getAction = function () {
13042 return this.action
;
13046 * Get the symbolic name of the mode or modes for which the action is configured to be available.
13048 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
13049 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
13052 * @return {string[]}
13054 OO
.ui
.ActionWidget
.prototype.getModes = function () {
13055 return this.modes
.slice();
13059 * Emit a resize event if the size has changed.
13064 OO
.ui
.ActionWidget
.prototype.propagateResize = function () {
13067 if ( this.isElementAttached() ) {
13068 width
= this.$element
.width();
13069 height
= this.$element
.height();
13071 if ( width
!== this.width
|| height
!== this.height
) {
13072 this.width
= width
;
13073 this.height
= height
;
13074 this.emit( 'resize' );
13084 OO
.ui
.ActionWidget
.prototype.setIcon = function () {
13086 OO
.ui
.mixin
.IconElement
.prototype.setIcon
.apply( this, arguments
);
13087 this.propagateResize();
13095 OO
.ui
.ActionWidget
.prototype.setLabel = function () {
13097 OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.apply( this, arguments
);
13098 this.propagateResize();
13106 OO
.ui
.ActionWidget
.prototype.setFlags = function () {
13108 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags
.apply( this, arguments
);
13109 this.propagateResize();
13117 OO
.ui
.ActionWidget
.prototype.clearFlags = function () {
13119 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags
.apply( this, arguments
);
13120 this.propagateResize();
13126 * Toggle the visibility of the action button.
13128 * @param {boolean} [show] Show button, omit to toggle visibility
13131 OO
.ui
.ActionWidget
.prototype.toggle = function () {
13133 OO
.ui
.ActionWidget
.parent
.prototype.toggle
.apply( this, arguments
);
13134 this.propagateResize();
13140 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
13141 * which is used to display additional information or options.
13144 * // Example of a popup button.
13145 * var popupButton = new OO.ui.PopupButtonWidget( {
13146 * label: 'Popup button with options',
13149 * $content: $( '<p>Additional options here.</p>' ),
13151 * align: 'force-left'
13154 * // Append the button to the DOM.
13155 * $( 'body' ).append( popupButton.$element );
13158 * @extends OO.ui.ButtonWidget
13159 * @mixins OO.ui.mixin.PopupElement
13162 * @param {Object} [config] Configuration options
13164 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
13165 // Parent constructor
13166 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
13168 // Mixin constructors
13169 OO
.ui
.mixin
.PopupElement
.call( this, config
);
13172 this.connect( this, { click
: 'onAction' } );
13176 .addClass( 'oo-ui-popupButtonWidget' )
13177 .attr( 'aria-haspopup', 'true' )
13178 .append( this.popup
.$element
);
13183 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
13184 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
13189 * Handle the button action being triggered.
13193 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
13194 this.popup
.toggle();
13198 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
13199 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
13200 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
13201 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
13202 * and {@link OO.ui.mixin.LabelElement labels}. Please see
13203 * the [OOjs UI documentation][1] on MediaWiki for more information.
13206 * // Toggle buttons in the 'off' and 'on' state.
13207 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
13208 * label: 'Toggle Button off'
13210 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
13211 * label: 'Toggle Button on',
13214 * // Append the buttons to the DOM.
13215 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
13217 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
13220 * @extends OO.ui.ToggleWidget
13221 * @mixins OO.ui.mixin.ButtonElement
13222 * @mixins OO.ui.mixin.IconElement
13223 * @mixins OO.ui.mixin.IndicatorElement
13224 * @mixins OO.ui.mixin.LabelElement
13225 * @mixins OO.ui.mixin.TitledElement
13226 * @mixins OO.ui.mixin.FlaggedElement
13227 * @mixins OO.ui.mixin.TabIndexedElement
13230 * @param {Object} [config] Configuration options
13231 * @cfg {boolean} [value=false] The toggle button’s initial on/off
13232 * state. By default, the button is in the 'off' state.
13234 OO
.ui
.ToggleButtonWidget
= function OoUiToggleButtonWidget( config
) {
13235 // Configuration initialization
13236 config
= config
|| {};
13238 // Parent constructor
13239 OO
.ui
.ToggleButtonWidget
.parent
.call( this, config
);
13241 // Mixin constructors
13242 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
13243 OO
.ui
.mixin
.IconElement
.call( this, config
);
13244 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
13245 OO
.ui
.mixin
.LabelElement
.call( this, config
);
13246 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
13247 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
13248 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
13251 this.connect( this, { click
: 'onAction' } );
13254 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
13256 .addClass( 'oo-ui-toggleButtonWidget' )
13257 .append( this.$button
);
13262 OO
.inheritClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.ToggleWidget
);
13263 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
13264 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.IconElement
);
13265 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
13266 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.LabelElement
);
13267 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.TitledElement
);
13268 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
13269 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13274 * Handle the button action being triggered.
13278 OO
.ui
.ToggleButtonWidget
.prototype.onAction = function () {
13279 this.setValue( !this.value
);
13285 OO
.ui
.ToggleButtonWidget
.prototype.setValue = function ( value
) {
13287 if ( value
!== this.value
) {
13288 // Might be called from parent constructor before ButtonElement constructor
13289 if ( this.$button
) {
13290 this.$button
.attr( 'aria-pressed', value
.toString() );
13292 this.setActive( value
);
13296 OO
.ui
.ToggleButtonWidget
.parent
.prototype.setValue
.call( this, value
);
13304 OO
.ui
.ToggleButtonWidget
.prototype.setButtonElement = function ( $button
) {
13305 if ( this.$button
) {
13306 this.$button
.removeAttr( 'aria-pressed' );
13308 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement
.call( this, $button
);
13309 this.$button
.attr( 'aria-pressed', this.value
.toString() );
13313 * CapsuleMultiSelectWidgets are something like a {@link OO.ui.ComboBoxInputWidget combo box widget}
13314 * that allows for selecting multiple values.
13316 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
13319 * // Example: A CapsuleMultiSelectWidget.
13320 * var capsule = new OO.ui.CapsuleMultiSelectWidget( {
13321 * label: 'CapsuleMultiSelectWidget',
13322 * selected: [ 'Option 1', 'Option 3' ],
13325 * new OO.ui.MenuOptionWidget( {
13326 * data: 'Option 1',
13327 * label: 'Option One'
13329 * new OO.ui.MenuOptionWidget( {
13330 * data: 'Option 2',
13331 * label: 'Option Two'
13333 * new OO.ui.MenuOptionWidget( {
13334 * data: 'Option 3',
13335 * label: 'Option Three'
13337 * new OO.ui.MenuOptionWidget( {
13338 * data: 'Option 4',
13339 * label: 'Option Four'
13341 * new OO.ui.MenuOptionWidget( {
13342 * data: 'Option 5',
13343 * label: 'Option Five'
13348 * $( 'body' ).append( capsule.$element );
13350 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13353 * @extends OO.ui.Widget
13354 * @mixins OO.ui.mixin.TabIndexedElement
13355 * @mixins OO.ui.mixin.GroupElement
13358 * @param {Object} [config] Configuration options
13359 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
13360 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
13361 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
13362 * If specified, this popup will be shown instead of the menu (but the menu
13363 * will still be used for item labels and allowArbitrary=false). The widgets
13364 * in the popup should use this.addItemsFromData() or this.addItems() as necessary.
13365 * @cfg {jQuery} [$overlay] Render the menu or popup into a separate layer.
13366 * This configuration is useful in cases where the expanded menu is larger than
13367 * its containing `<div>`. The specified overlay layer is usually on top of
13368 * the containing `<div>` and has a larger area. By default, the menu uses
13369 * relative positioning.
13371 OO
.ui
.CapsuleMultiSelectWidget
= function OoUiCapsuleMultiSelectWidget( config
) {
13374 // Configuration initialization
13375 config
= config
|| {};
13377 // Parent constructor
13378 OO
.ui
.CapsuleMultiSelectWidget
.parent
.call( this, config
);
13380 // Properties (must be set before mixin constructor calls)
13381 this.$input
= config
.popup
? null : $( '<input>' );
13382 this.$handle
= $( '<div>' );
13384 // Mixin constructors
13385 OO
.ui
.mixin
.GroupElement
.call( this, config
);
13386 if ( config
.popup
) {
13387 config
.popup
= $.extend( {}, config
.popup
, {
13391 OO
.ui
.mixin
.PopupElement
.call( this, config
);
13392 $tabFocus
= $( '<span>' );
13393 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: $tabFocus
} ) );
13397 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
13399 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
13400 OO
.ui
.mixin
.IconElement
.call( this, config
);
13403 this.allowArbitrary
= !!config
.allowArbitrary
;
13404 this.$overlay
= config
.$overlay
|| this.$element
;
13405 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
13408 $input
: this.$input
,
13409 $container
: this.$element
,
13410 filterFromInput
: true,
13411 disabled
: this.isDisabled()
13417 if ( this.popup
) {
13419 focus
: this.onFocusForPopup
.bind( this )
13421 this.popup
.$element
.on( 'focusout', this.onPopupFocusOut
.bind( this ) );
13422 if ( this.popup
.$autoCloseIgnore
) {
13423 this.popup
.$autoCloseIgnore
.on( 'focusout', this.onPopupFocusOut
.bind( this ) );
13425 this.popup
.connect( this, {
13426 toggle: function ( visible
) {
13427 $tabFocus
.toggle( !visible
);
13432 focus
: this.onInputFocus
.bind( this ),
13433 blur
: this.onInputBlur
.bind( this ),
13434 'propertychange change click mouseup keydown keyup input cut paste select': this.onInputChange
.bind( this ),
13435 keydown
: this.onKeyDown
.bind( this ),
13436 keypress
: this.onKeyPress
.bind( this )
13439 this.menu
.connect( this, {
13440 choose
: 'onMenuChoose',
13441 add
: 'onMenuItemsChange',
13442 remove
: 'onMenuItemsChange'
13445 click
: this.onClick
.bind( this )
13449 if ( this.$input
) {
13450 this.$input
.prop( 'disabled', this.isDisabled() );
13451 this.$input
.attr( {
13453 'aria-autocomplete': 'list'
13455 this.$input
.width( '1em' );
13457 if ( config
.data
) {
13458 this.setItemsFromData( config
.data
);
13460 this.$group
.addClass( 'oo-ui-capsuleMultiSelectWidget-group' );
13461 this.$handle
.addClass( 'oo-ui-capsuleMultiSelectWidget-handle' )
13462 .append( this.$indicator
, this.$icon
, this.$group
);
13463 this.$element
.addClass( 'oo-ui-capsuleMultiSelectWidget' )
13464 .append( this.$handle
);
13465 if ( this.popup
) {
13466 this.$handle
.append( $tabFocus
);
13467 this.$overlay
.append( this.popup
.$element
);
13469 this.$handle
.append( this.$input
);
13470 this.$overlay
.append( this.menu
.$element
);
13472 this.onMenuItemsChange();
13477 OO
.inheritClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.Widget
);
13478 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.GroupElement
);
13479 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.PopupElement
);
13480 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13481 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.IndicatorElement
);
13482 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.IconElement
);
13489 * A change event is emitted when the set of selected items changes.
13491 * @param {Mixed[]} datas Data of the now-selected items
13497 * Construct a OO.ui.CapsuleItemWidget (or a subclass thereof) from given label and data.
13500 * @param {Mixed} data Custom data of any type.
13501 * @param {string} label The label text.
13502 * @return {OO.ui.CapsuleItemWidget}
13504 OO
.ui
.CapsuleMultiSelectWidget
.prototype.createItemWidget = function ( data
, label
) {
13505 return new OO
.ui
.CapsuleItemWidget( { data
: data
, label
: label
} );
13509 * Get the data of the items in the capsule
13510 * @return {Mixed[]}
13512 OO
.ui
.CapsuleMultiSelectWidget
.prototype.getItemsData = function () {
13513 return $.map( this.getItems(), function ( e
) { return e
.data
; } );
13517 * Set the items in the capsule by providing data
13519 * @param {Mixed[]} datas
13520 * @return {OO.ui.CapsuleMultiSelectWidget}
13522 OO
.ui
.CapsuleMultiSelectWidget
.prototype.setItemsFromData = function ( datas
) {
13525 items
= this.getItems();
13527 $.each( datas
, function ( i
, data
) {
13529 item
= menu
.getItemFromData( data
);
13532 label
= item
.label
;
13533 } else if ( widget
.allowArbitrary
) {
13534 label
= String( data
);
13540 for ( j
= 0; j
< items
.length
; j
++ ) {
13541 if ( items
[ j
].data
=== data
&& items
[ j
].label
=== label
) {
13543 items
.splice( j
, 1 );
13548 item
= widget
.createItemWidget( data
, label
);
13550 widget
.addItems( [ item
], i
);
13553 if ( items
.length
) {
13554 widget
.removeItems( items
);
13561 * Add items to the capsule by providing their data
13563 * @param {Mixed[]} datas
13564 * @return {OO.ui.CapsuleMultiSelectWidget}
13566 OO
.ui
.CapsuleMultiSelectWidget
.prototype.addItemsFromData = function ( datas
) {
13571 $.each( datas
, function ( i
, data
) {
13574 if ( !widget
.getItemFromData( data
) ) {
13575 item
= menu
.getItemFromData( data
);
13577 items
.push( widget
.createItemWidget( data
, item
.label
) );
13578 } else if ( widget
.allowArbitrary
) {
13579 items
.push( widget
.createItemWidget( data
, String( data
) ) );
13584 if ( items
.length
) {
13585 this.addItems( items
);
13592 * Remove items by data
13594 * @param {Mixed[]} datas
13595 * @return {OO.ui.CapsuleMultiSelectWidget}
13597 OO
.ui
.CapsuleMultiSelectWidget
.prototype.removeItemsFromData = function ( datas
) {
13601 $.each( datas
, function ( i
, data
) {
13602 var item
= widget
.getItemFromData( data
);
13604 items
.push( item
);
13608 if ( items
.length
) {
13609 this.removeItems( items
);
13618 OO
.ui
.CapsuleMultiSelectWidget
.prototype.addItems = function ( items
) {
13620 oldItems
= this.items
.slice();
13622 OO
.ui
.mixin
.GroupElement
.prototype.addItems
.call( this, items
);
13624 if ( this.items
.length
!== oldItems
.length
) {
13628 for ( i
= 0, l
= oldItems
.length
; same
&& i
< l
; i
++ ) {
13629 same
= same
&& this.items
[ i
] === oldItems
[ i
];
13633 this.emit( 'change', this.getItemsData() );
13642 OO
.ui
.CapsuleMultiSelectWidget
.prototype.removeItems = function ( items
) {
13644 oldItems
= this.items
.slice();
13646 OO
.ui
.mixin
.GroupElement
.prototype.removeItems
.call( this, items
);
13648 if ( this.items
.length
!== oldItems
.length
) {
13652 for ( i
= 0, l
= oldItems
.length
; same
&& i
< l
; i
++ ) {
13653 same
= same
&& this.items
[ i
] === oldItems
[ i
];
13657 this.emit( 'change', this.getItemsData() );
13666 OO
.ui
.CapsuleMultiSelectWidget
.prototype.clearItems = function () {
13667 if ( this.items
.length
) {
13668 OO
.ui
.mixin
.GroupElement
.prototype.clearItems
.call( this );
13669 this.emit( 'change', this.getItemsData() );
13675 * Get the capsule widget's menu.
13676 * @return {OO.ui.MenuSelectWidget} Menu widget
13678 OO
.ui
.CapsuleMultiSelectWidget
.prototype.getMenu = function () {
13683 * Handle focus events
13686 * @param {jQuery.Event} event
13688 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onInputFocus = function () {
13689 if ( !this.isDisabled() ) {
13690 this.menu
.toggle( true );
13695 * Handle blur events
13698 * @param {jQuery.Event} event
13700 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onInputBlur = function () {
13701 if ( this.allowArbitrary
&& this.$input
.val().trim() !== '' ) {
13702 this.addItemsFromData( [ this.$input
.val() ] );
13708 * Handle focus events
13711 * @param {jQuery.Event} event
13713 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onFocusForPopup = function () {
13714 if ( !this.isDisabled() ) {
13715 this.popup
.setSize( this.$handle
.width() );
13716 this.popup
.toggle( true );
13717 this.popup
.$element
.find( '*' )
13718 .filter( function () { return OO
.ui
.isFocusableElement( $( this ), true ); } )
13725 * Handles popup focus out events.
13728 * @param {Event} e Focus out event
13730 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onPopupFocusOut = function () {
13731 var widget
= this.popup
;
13733 setTimeout( function () {
13735 widget
.isVisible() &&
13736 !OO
.ui
.contains( widget
.$element
[ 0 ], document
.activeElement
, true ) &&
13737 ( !widget
.$autoCloseIgnore
|| !widget
.$autoCloseIgnore
.has( document
.activeElement
).length
)
13739 widget
.toggle( false );
13745 * Handle mouse click events.
13748 * @param {jQuery.Event} e Mouse click event
13750 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onClick = function ( e
) {
13751 if ( e
.which
=== 1 ) {
13758 * Handle key press events.
13761 * @param {jQuery.Event} e Key press event
13763 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onKeyPress = function ( e
) {
13766 if ( !this.isDisabled() ) {
13767 if ( e
.which
=== OO
.ui
.Keys
.ESCAPE
) {
13772 if ( !this.popup
) {
13773 this.menu
.toggle( true );
13774 if ( e
.which
=== OO
.ui
.Keys
.ENTER
) {
13775 item
= this.menu
.getItemFromLabel( this.$input
.val(), true );
13777 this.addItemsFromData( [ item
.data
] );
13779 } else if ( this.allowArbitrary
&& this.$input
.val().trim() !== '' ) {
13780 this.addItemsFromData( [ this.$input
.val() ] );
13786 // Make sure the input gets resized.
13787 setTimeout( this.onInputChange
.bind( this ), 0 );
13793 * Handle key down events.
13796 * @param {jQuery.Event} e Key down event
13798 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onKeyDown = function ( e
) {
13799 if ( !this.isDisabled() ) {
13800 // 'keypress' event is not triggered for Backspace
13801 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.$input
.val() === '' ) {
13802 if ( this.items
.length
) {
13803 this.removeItems( this.items
.slice( -1 ) );
13811 * Handle input change events.
13814 * @param {jQuery.Event} e Event of some sort
13816 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onInputChange = function () {
13817 if ( !this.isDisabled() ) {
13818 this.$input
.width( this.$input
.val().length
+ 'em' );
13823 * Handle menu choose events.
13826 * @param {OO.ui.OptionWidget} item Chosen item
13828 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onMenuChoose = function ( item
) {
13829 if ( item
&& item
.isVisible() ) {
13830 this.addItemsFromData( [ item
.getData() ] );
13836 * Handle menu item change events.
13840 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onMenuItemsChange = function () {
13841 this.setItemsFromData( this.getItemsData() );
13842 this.$element
.toggleClass( 'oo-ui-capsuleMultiSelectWidget-empty', this.menu
.isEmpty() );
13846 * Clear the input field
13849 OO
.ui
.CapsuleMultiSelectWidget
.prototype.clearInput = function () {
13850 if ( this.$input
) {
13851 this.$input
.val( '' );
13852 this.$input
.width( '1em' );
13854 if ( this.popup
) {
13855 this.popup
.toggle( false );
13857 this.menu
.toggle( false );
13858 this.menu
.selectItem();
13859 this.menu
.highlightItem();
13865 OO
.ui
.CapsuleMultiSelectWidget
.prototype.setDisabled = function ( disabled
) {
13869 OO
.ui
.CapsuleMultiSelectWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
13871 if ( this.$input
) {
13872 this.$input
.prop( 'disabled', this.isDisabled() );
13875 this.menu
.setDisabled( this.isDisabled() );
13877 if ( this.popup
) {
13878 this.popup
.setDisabled( this.isDisabled() );
13881 if ( this.items
) {
13882 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
13883 this.items
[ i
].updateDisabled();
13893 * @return {OO.ui.CapsuleMultiSelectWidget}
13895 OO
.ui
.CapsuleMultiSelectWidget
.prototype.focus = function () {
13896 if ( !this.isDisabled() ) {
13897 if ( this.popup
) {
13898 this.popup
.setSize( this.$handle
.width() );
13899 this.popup
.toggle( true );
13900 this.popup
.$element
.find( '*' )
13901 .filter( function () { return OO
.ui
.isFocusableElement( $( this ), true ); } )
13905 this.menu
.toggle( true );
13906 this.$input
.focus();
13913 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiSelectWidget
13914 * CapsuleMultiSelectWidget} to display the selected items.
13917 * @extends OO.ui.Widget
13918 * @mixins OO.ui.mixin.ItemWidget
13919 * @mixins OO.ui.mixin.IndicatorElement
13920 * @mixins OO.ui.mixin.LabelElement
13921 * @mixins OO.ui.mixin.FlaggedElement
13922 * @mixins OO.ui.mixin.TabIndexedElement
13925 * @param {Object} [config] Configuration options
13927 OO
.ui
.CapsuleItemWidget
= function OoUiCapsuleItemWidget( config
) {
13928 // Configuration initialization
13929 config
= config
|| {};
13931 // Parent constructor
13932 OO
.ui
.CapsuleItemWidget
.parent
.call( this, config
);
13934 // Properties (must be set before mixin constructor calls)
13935 this.$indicator
= $( '<span>' );
13937 // Mixin constructors
13938 OO
.ui
.mixin
.ItemWidget
.call( this );
13939 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$indicator
, indicator
: 'clear' } ) );
13940 OO
.ui
.mixin
.LabelElement
.call( this, config
);
13941 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
13942 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$indicator
} ) );
13945 this.$indicator
.on( {
13946 keydown
: this.onCloseKeyDown
.bind( this ),
13947 click
: this.onCloseClick
.bind( this )
13952 .addClass( 'oo-ui-capsuleItemWidget' )
13953 .append( this.$indicator
, this.$label
);
13958 OO
.inheritClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.Widget
);
13959 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.ItemWidget
);
13960 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.IndicatorElement
);
13961 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.LabelElement
);
13962 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.FlaggedElement
);
13963 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13968 * Handle close icon clicks
13969 * @param {jQuery.Event} event
13971 OO
.ui
.CapsuleItemWidget
.prototype.onCloseClick = function () {
13972 var element
= this.getElementGroup();
13974 if ( !this.isDisabled() && element
&& $.isFunction( element
.removeItems
) ) {
13975 element
.removeItems( [ this ] );
13981 * Handle close keyboard events
13982 * @param {jQuery.Event} event Key down event
13984 OO
.ui
.CapsuleItemWidget
.prototype.onCloseKeyDown = function ( e
) {
13985 if ( !this.isDisabled() && $.isFunction( this.getElementGroup().removeItems
) ) {
13986 switch ( e
.which
) {
13987 case OO
.ui
.Keys
.ENTER
:
13988 case OO
.ui
.Keys
.BACKSPACE
:
13989 case OO
.ui
.Keys
.SPACE
:
13990 this.getElementGroup().removeItems( [ this ] );
13997 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
13998 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
13999 * users can interact with it.
14001 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
14002 * OO.ui.DropdownInputWidget instead.
14005 * // Example: A DropdownWidget with a menu that contains three options
14006 * var dropDown = new OO.ui.DropdownWidget( {
14007 * label: 'Dropdown menu: Select a menu option',
14010 * new OO.ui.MenuOptionWidget( {
14014 * new OO.ui.MenuOptionWidget( {
14018 * new OO.ui.MenuOptionWidget( {
14026 * $( 'body' ).append( dropDown.$element );
14028 * dropDown.getMenu().selectItemByData( 'b' );
14030 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
14032 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
14034 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
14037 * @extends OO.ui.Widget
14038 * @mixins OO.ui.mixin.IconElement
14039 * @mixins OO.ui.mixin.IndicatorElement
14040 * @mixins OO.ui.mixin.LabelElement
14041 * @mixins OO.ui.mixin.TitledElement
14042 * @mixins OO.ui.mixin.TabIndexedElement
14045 * @param {Object} [config] Configuration options
14046 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
14047 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
14048 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
14049 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
14051 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
14052 // Configuration initialization
14053 config
= $.extend( { indicator
: 'down' }, config
);
14055 // Parent constructor
14056 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
14058 // Properties (must be set before TabIndexedElement constructor call)
14059 this.$handle
= this.$( '<span>' );
14060 this.$overlay
= config
.$overlay
|| this.$element
;
14062 // Mixin constructors
14063 OO
.ui
.mixin
.IconElement
.call( this, config
);
14064 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
14065 OO
.ui
.mixin
.LabelElement
.call( this, config
);
14066 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
14067 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
14070 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend( {
14072 $container
: this.$element
14073 }, config
.menu
) );
14077 click
: this.onClick
.bind( this ),
14078 keypress
: this.onKeyPress
.bind( this )
14080 this.menu
.connect( this, { select
: 'onMenuSelect' } );
14084 .addClass( 'oo-ui-dropdownWidget-handle' )
14085 .append( this.$icon
, this.$label
, this.$indicator
);
14087 .addClass( 'oo-ui-dropdownWidget' )
14088 .append( this.$handle
);
14089 this.$overlay
.append( this.menu
.$element
);
14094 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
14095 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
14096 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
14097 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
14098 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
14099 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
14106 * @return {OO.ui.MenuSelectWidget} Menu of widget
14108 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
14113 * Handles menu select events.
14116 * @param {OO.ui.MenuOptionWidget} item Selected menu item
14118 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
14122 this.setLabel( null );
14126 selectedLabel
= item
.getLabel();
14128 // If the label is a DOM element, clone it, because setLabel will append() it
14129 if ( selectedLabel
instanceof jQuery
) {
14130 selectedLabel
= selectedLabel
.clone();
14133 this.setLabel( selectedLabel
);
14137 * Handle mouse click events.
14140 * @param {jQuery.Event} e Mouse click event
14142 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
14143 if ( !this.isDisabled() && e
.which
=== 1 ) {
14144 this.menu
.toggle();
14150 * Handle key press events.
14153 * @param {jQuery.Event} e Key press event
14155 OO
.ui
.DropdownWidget
.prototype.onKeyPress = function ( e
) {
14156 if ( !this.isDisabled() &&
14157 ( ( e
.which
=== OO
.ui
.Keys
.SPACE
&& !this.menu
.isVisible() ) || e
.which
=== OO
.ui
.Keys
.ENTER
)
14159 this.menu
.toggle();
14165 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
14166 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
14167 * OO.ui.mixin.IndicatorElement indicators}.
14168 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14171 * // Example of a file select widget
14172 * var selectFile = new OO.ui.SelectFileWidget();
14173 * $( 'body' ).append( selectFile.$element );
14175 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
14178 * @extends OO.ui.Widget
14179 * @mixins OO.ui.mixin.IconElement
14180 * @mixins OO.ui.mixin.IndicatorElement
14181 * @mixins OO.ui.mixin.PendingElement
14182 * @mixins OO.ui.mixin.LabelElement
14185 * @param {Object} [config] Configuration options
14186 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
14187 * @cfg {string} [placeholder] Text to display when no file is selected.
14188 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
14189 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
14190 * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
14191 * @cfg {boolean} [dragDropUI=false] Deprecated alias for showDropTarget
14193 OO
.ui
.SelectFileWidget
= function OoUiSelectFileWidget( config
) {
14196 // TODO: Remove in next release
14197 if ( config
&& config
.dragDropUI
) {
14198 config
.showDropTarget
= true;
14201 // Configuration initialization
14202 config
= $.extend( {
14204 placeholder
: OO
.ui
.msg( 'ooui-selectfile-placeholder' ),
14205 notsupported
: OO
.ui
.msg( 'ooui-selectfile-not-supported' ),
14207 showDropTarget
: false
14210 // Parent constructor
14211 OO
.ui
.SelectFileWidget
.parent
.call( this, config
);
14213 // Mixin constructors
14214 OO
.ui
.mixin
.IconElement
.call( this, config
);
14215 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
14216 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$info
} ) );
14217 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { autoFitLabel
: true } ) );
14220 this.$info
= $( '<span>' );
14223 this.showDropTarget
= config
.showDropTarget
;
14224 this.isSupported
= this.constructor.static.isSupported();
14225 this.currentFile
= null;
14226 if ( Array
.isArray( config
.accept
) ) {
14227 this.accept
= config
.accept
;
14229 this.accept
= null;
14231 this.placeholder
= config
.placeholder
;
14232 this.notsupported
= config
.notsupported
;
14233 this.onFileSelectedHandler
= this.onFileSelected
.bind( this );
14235 this.selectButton
= new OO
.ui
.ButtonWidget( {
14236 classes
: [ 'oo-ui-selectFileWidget-selectButton' ],
14237 label
: OO
.ui
.msg( 'ooui-selectfile-button-select' ),
14238 disabled
: this.disabled
|| !this.isSupported
14241 this.clearButton
= new OO
.ui
.ButtonWidget( {
14242 classes
: [ 'oo-ui-selectFileWidget-clearButton' ],
14245 disabled
: this.disabled
14249 this.selectButton
.$button
.on( {
14250 keypress
: this.onKeyPress
.bind( this )
14252 this.clearButton
.connect( this, {
14253 click
: 'onClearClick'
14255 if ( config
.droppable
) {
14256 dragHandler
= this.onDragEnterOrOver
.bind( this );
14257 this.$element
.on( {
14258 dragenter
: dragHandler
,
14259 dragover
: dragHandler
,
14260 dragleave
: this.onDragLeave
.bind( this ),
14261 drop
: this.onDrop
.bind( this )
14268 this.$label
.addClass( 'oo-ui-selectFileWidget-label' );
14270 .addClass( 'oo-ui-selectFileWidget-info' )
14271 .append( this.$icon
, this.$label
, this.clearButton
.$element
, this.$indicator
);
14273 .addClass( 'oo-ui-selectFileWidget' )
14274 .append( this.$info
, this.selectButton
.$element
);
14275 if ( config
.droppable
&& config
.showDropTarget
) {
14276 this.$dropTarget
= $( '<div>' )
14277 .addClass( 'oo-ui-selectFileWidget-dropTarget' )
14278 .text( OO
.ui
.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
14280 click
: this.onDropTargetClick
.bind( this )
14282 this.$element
.prepend( this.$dropTarget
);
14288 OO
.inheritClass( OO
.ui
.SelectFileWidget
, OO
.ui
.Widget
);
14289 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.IconElement
);
14290 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.IndicatorElement
);
14291 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.PendingElement
);
14292 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.LabelElement
);
14294 /* Static Properties */
14297 * Check if this widget is supported
14300 * @return {boolean}
14302 OO
.ui
.SelectFileWidget
.static.isSupported = function () {
14304 if ( OO
.ui
.SelectFileWidget
.static.isSupportedCache
=== null ) {
14305 $input
= $( '<input type="file">' );
14306 OO
.ui
.SelectFileWidget
.static.isSupportedCache
= $input
[ 0 ].files
!== undefined;
14308 return OO
.ui
.SelectFileWidget
.static.isSupportedCache
;
14311 OO
.ui
.SelectFileWidget
.static.isSupportedCache
= null;
14318 * A change event is emitted when the on/off state of the toggle changes.
14320 * @param {File|null} value New value
14326 * Get the current value of the field
14328 * @return {File|null}
14330 OO
.ui
.SelectFileWidget
.prototype.getValue = function () {
14331 return this.currentFile
;
14335 * Set the current value of the field
14337 * @param {File|null} file File to select
14339 OO
.ui
.SelectFileWidget
.prototype.setValue = function ( file
) {
14340 if ( this.currentFile
!== file
) {
14341 this.currentFile
= file
;
14343 this.emit( 'change', this.currentFile
);
14348 * Focus the widget.
14350 * Focusses the select file button.
14354 OO
.ui
.SelectFileWidget
.prototype.focus = function () {
14355 this.selectButton
.$button
[ 0 ].focus();
14360 * Update the user interface when a file is selected or unselected
14364 OO
.ui
.SelectFileWidget
.prototype.updateUI = function () {
14366 if ( !this.isSupported
) {
14367 this.$element
.addClass( 'oo-ui-selectFileWidget-notsupported' );
14368 this.$element
.removeClass( 'oo-ui-selectFileWidget-empty' );
14369 this.setLabel( this.notsupported
);
14371 this.$element
.addClass( 'oo-ui-selectFileWidget-supported' );
14372 if ( this.currentFile
) {
14373 this.$element
.removeClass( 'oo-ui-selectFileWidget-empty' );
14375 if ( this.currentFile
.type
!== '' ) {
14376 $label
= $label
.add( $( '<span>' ).addClass( 'oo-ui-selectFileWidget-fileType' ).text( this.currentFile
.type
) );
14378 $label
= $label
.add( $( '<span>' ).text( this.currentFile
.name
) );
14379 this.setLabel( $label
);
14381 this.$element
.addClass( 'oo-ui-selectFileWidget-empty' );
14382 this.setLabel( this.placeholder
);
14388 * Add the input to the widget
14392 OO
.ui
.SelectFileWidget
.prototype.addInput = function () {
14393 if ( this.$input
) {
14394 this.$input
.remove();
14397 if ( !this.isSupported
) {
14398 this.$input
= null;
14402 this.$input
= $( '<input type="file">' );
14403 this.$input
.on( 'change', this.onFileSelectedHandler
);
14404 this.$input
.attr( {
14407 if ( this.accept
) {
14408 this.$input
.attr( 'accept', this.accept
.join( ', ' ) );
14410 this.selectButton
.$button
.append( this.$input
);
14414 * Determine if we should accept this file
14417 * @param {string} File MIME type
14418 * @return {boolean}
14420 OO
.ui
.SelectFileWidget
.prototype.isAllowedType = function ( mimeType
) {
14423 if ( !this.accept
|| !mimeType
) {
14427 for ( i
= 0; i
< this.accept
.length
; i
++ ) {
14428 mimeTest
= this.accept
[ i
];
14429 if ( mimeTest
=== mimeType
) {
14431 } else if ( mimeTest
.substr( -2 ) === '/*' ) {
14432 mimeTest
= mimeTest
.substr( 0, mimeTest
.length
- 1 );
14433 if ( mimeType
.substr( 0, mimeTest
.length
) === mimeTest
) {
14443 * Handle file selection from the input
14446 * @param {jQuery.Event} e
14448 OO
.ui
.SelectFileWidget
.prototype.onFileSelected = function ( e
) {
14449 var file
= OO
.getProp( e
.target
, 'files', 0 ) || null;
14451 if ( file
&& !this.isAllowedType( file
.type
) ) {
14455 this.setValue( file
);
14460 * Handle clear button click events.
14464 OO
.ui
.SelectFileWidget
.prototype.onClearClick = function () {
14465 this.setValue( null );
14470 * Handle key press events.
14473 * @param {jQuery.Event} e Key press event
14475 OO
.ui
.SelectFileWidget
.prototype.onKeyPress = function ( e
) {
14476 if ( this.isSupported
&& !this.isDisabled() && this.$input
&&
14477 ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
14479 this.$input
.click();
14485 * Handle drop target click events.
14488 * @param {jQuery.Event} e Key press event
14490 OO
.ui
.SelectFileWidget
.prototype.onDropTargetClick = function () {
14491 if ( this.isSupported
&& !this.isDisabled() && this.$input
) {
14492 this.$input
.click();
14498 * Handle drag enter and over events
14501 * @param {jQuery.Event} e Drag event
14503 OO
.ui
.SelectFileWidget
.prototype.onDragEnterOrOver = function ( e
) {
14505 droppableFile
= false,
14506 dt
= e
.originalEvent
.dataTransfer
;
14508 e
.preventDefault();
14509 e
.stopPropagation();
14511 if ( this.isDisabled() || !this.isSupported
) {
14512 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14513 dt
.dropEffect
= 'none';
14517 // DataTransferItem and File both have a type property, but in Chrome files
14518 // have no information at this point.
14519 itemOrFile
= OO
.getProp( dt
, 'items', 0 ) || OO
.getProp( dt
, 'files', 0 );
14520 if ( itemOrFile
) {
14521 if ( this.isAllowedType( itemOrFile
.type
) ) {
14522 droppableFile
= true;
14524 // dt.types is Array-like, but not an Array
14525 } else if ( Array
.prototype.indexOf
.call( OO
.getProp( dt
, 'types' ) || [], 'Files' ) !== -1 ) {
14526 // File information is not available at this point for security so just assume
14527 // it is acceptable for now.
14528 // https://bugzilla.mozilla.org/show_bug.cgi?id=640534
14529 droppableFile
= true;
14532 this.$element
.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile
);
14533 if ( !droppableFile
) {
14534 dt
.dropEffect
= 'none';
14541 * Handle drag leave events
14544 * @param {jQuery.Event} e Drag event
14546 OO
.ui
.SelectFileWidget
.prototype.onDragLeave = function () {
14547 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14551 * Handle drop events
14554 * @param {jQuery.Event} e Drop event
14556 OO
.ui
.SelectFileWidget
.prototype.onDrop = function ( e
) {
14558 dt
= e
.originalEvent
.dataTransfer
;
14560 e
.preventDefault();
14561 e
.stopPropagation();
14562 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14564 if ( this.isDisabled() || !this.isSupported
) {
14568 file
= OO
.getProp( dt
, 'files', 0 );
14569 if ( file
&& !this.isAllowedType( file
.type
) ) {
14573 this.setValue( file
);
14582 OO
.ui
.SelectFileWidget
.prototype.setDisabled = function ( disabled
) {
14583 OO
.ui
.SelectFileWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
14584 if ( this.selectButton
) {
14585 this.selectButton
.setDisabled( disabled
);
14587 if ( this.clearButton
) {
14588 this.clearButton
.setDisabled( disabled
);
14594 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
14595 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
14596 * for a list of icons included in the library.
14599 * // An icon widget with a label
14600 * var myIcon = new OO.ui.IconWidget( {
14602 * iconTitle: 'Help'
14604 * // Create a label.
14605 * var iconLabel = new OO.ui.LabelWidget( {
14608 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
14610 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
14613 * @extends OO.ui.Widget
14614 * @mixins OO.ui.mixin.IconElement
14615 * @mixins OO.ui.mixin.TitledElement
14616 * @mixins OO.ui.mixin.FlaggedElement
14619 * @param {Object} [config] Configuration options
14621 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
14622 // Configuration initialization
14623 config
= config
|| {};
14625 // Parent constructor
14626 OO
.ui
.IconWidget
.parent
.call( this, config
);
14628 // Mixin constructors
14629 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
14630 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
14631 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
14634 this.$element
.addClass( 'oo-ui-iconWidget' );
14639 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
14640 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
14641 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
14642 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
14644 /* Static Properties */
14646 OO
.ui
.IconWidget
.static.tagName
= 'span';
14649 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
14650 * attention to the status of an item or to clarify the function of a control. For a list of
14651 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
14654 * // Example of an indicator widget
14655 * var indicator1 = new OO.ui.IndicatorWidget( {
14656 * indicator: 'alert'
14659 * // Create a fieldset layout to add a label
14660 * var fieldset = new OO.ui.FieldsetLayout();
14661 * fieldset.addItems( [
14662 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
14664 * $( 'body' ).append( fieldset.$element );
14666 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
14669 * @extends OO.ui.Widget
14670 * @mixins OO.ui.mixin.IndicatorElement
14671 * @mixins OO.ui.mixin.TitledElement
14674 * @param {Object} [config] Configuration options
14676 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
14677 // Configuration initialization
14678 config
= config
|| {};
14680 // Parent constructor
14681 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
14683 // Mixin constructors
14684 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
14685 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
14688 this.$element
.addClass( 'oo-ui-indicatorWidget' );
14693 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
14694 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
14695 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
14697 /* Static Properties */
14699 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
14702 * InputWidget is the base class for all input widgets, which
14703 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
14704 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
14705 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14707 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14711 * @extends OO.ui.Widget
14712 * @mixins OO.ui.mixin.FlaggedElement
14713 * @mixins OO.ui.mixin.TabIndexedElement
14714 * @mixins OO.ui.mixin.TitledElement
14715 * @mixins OO.ui.mixin.AccessKeyedElement
14718 * @param {Object} [config] Configuration options
14719 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
14720 * @cfg {string} [value=''] The value of the input.
14721 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
14722 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
14723 * before it is accepted.
14725 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
14726 // Configuration initialization
14727 config
= config
|| {};
14729 // Parent constructor
14730 OO
.ui
.InputWidget
.parent
.call( this, config
);
14733 this.$input
= this.getInputElement( config
);
14735 this.inputFilter
= config
.inputFilter
;
14737 // Mixin constructors
14738 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
14739 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
14740 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
14741 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$input
} ) );
14744 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
14748 .addClass( 'oo-ui-inputWidget-input' )
14749 .attr( 'name', config
.name
)
14750 .prop( 'disabled', this.isDisabled() );
14752 .addClass( 'oo-ui-inputWidget' )
14753 .append( this.$input
);
14754 this.setValue( config
.value
);
14755 this.setAccessKey( config
.accessKey
);
14756 if ( config
.dir
) {
14757 this.setDir( config
.dir
);
14763 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
14764 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
14765 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
14766 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
14767 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
14769 /* Static Properties */
14771 OO
.ui
.InputWidget
.static.supportsSimpleLabel
= true;
14773 /* Static Methods */
14778 OO
.ui
.InputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
14779 config
= OO
.ui
.InputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
14780 // Reusing $input lets browsers preserve inputted values across page reloads (T114134)
14781 config
.$input
= $( node
).find( '.oo-ui-inputWidget-input' );
14788 OO
.ui
.InputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
14789 var state
= OO
.ui
.InputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
14790 state
.value
= config
.$input
.val();
14791 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
14792 state
.focus
= config
.$input
.is( ':focus' );
14801 * A change event is emitted when the value of the input changes.
14803 * @param {string} value
14809 * Get input element.
14811 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
14812 * different circumstances. The element must have a `value` property (like form elements).
14815 * @param {Object} config Configuration options
14816 * @return {jQuery} Input element
14818 OO
.ui
.InputWidget
.prototype.getInputElement = function ( config
) {
14819 // See #reusePreInfuseDOM about config.$input
14820 return config
.$input
|| $( '<input>' );
14824 * Handle potentially value-changing events.
14827 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
14829 OO
.ui
.InputWidget
.prototype.onEdit = function () {
14831 if ( !this.isDisabled() ) {
14832 // Allow the stack to clear so the value will be updated
14833 setTimeout( function () {
14834 widget
.setValue( widget
.$input
.val() );
14840 * Get the value of the input.
14842 * @return {string} Input value
14844 OO
.ui
.InputWidget
.prototype.getValue = function () {
14845 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14846 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14847 var value
= this.$input
.val();
14848 if ( this.value
!== value
) {
14849 this.setValue( value
);
14855 * Set the directionality of the input, either RTL (right-to-left) or LTR (left-to-right).
14857 * @deprecated since v0.13.1, use #setDir directly
14858 * @param {boolean} isRTL Directionality is right-to-left
14861 OO
.ui
.InputWidget
.prototype.setRTL = function ( isRTL
) {
14862 this.setDir( isRTL
? 'rtl' : 'ltr' );
14867 * Set the directionality of the input.
14869 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
14872 OO
.ui
.InputWidget
.prototype.setDir = function ( dir
) {
14873 this.$input
.prop( 'dir', dir
);
14878 * Set the value of the input.
14880 * @param {string} value New value
14884 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
14885 value
= this.cleanUpValue( value
);
14886 // Update the DOM if it has changed. Note that with cleanUpValue, it
14887 // is possible for the DOM value to change without this.value changing.
14888 if ( this.$input
.val() !== value
) {
14889 this.$input
.val( value
);
14891 if ( this.value
!== value
) {
14892 this.value
= value
;
14893 this.emit( 'change', this.value
);
14899 * Set the input's access key.
14900 * FIXME: This is the same code as in OO.ui.mixin.ButtonElement, maybe find a better place for it?
14902 * @param {string} accessKey Input's access key, use empty string to remove
14905 OO
.ui
.InputWidget
.prototype.setAccessKey = function ( accessKey
) {
14906 accessKey
= typeof accessKey
=== 'string' && accessKey
.length
? accessKey
: null;
14908 if ( this.accessKey
!== accessKey
) {
14909 if ( this.$input
) {
14910 if ( accessKey
!== null ) {
14911 this.$input
.attr( 'accesskey', accessKey
);
14913 this.$input
.removeAttr( 'accesskey' );
14916 this.accessKey
= accessKey
;
14923 * Clean up incoming value.
14925 * Ensures value is a string, and converts undefined and null to empty string.
14928 * @param {string} value Original value
14929 * @return {string} Cleaned up value
14931 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
14932 if ( value
=== undefined || value
=== null ) {
14934 } else if ( this.inputFilter
) {
14935 return this.inputFilter( String( value
) );
14937 return String( value
);
14942 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
14943 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
14946 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
14947 if ( !this.isDisabled() ) {
14948 if ( this.$input
.is( ':checkbox, :radio' ) ) {
14949 this.$input
.click();
14951 if ( this.$input
.is( ':input' ) ) {
14952 this.$input
[ 0 ].focus();
14960 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
14961 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
14962 if ( this.$input
) {
14963 this.$input
.prop( 'disabled', this.isDisabled() );
14973 OO
.ui
.InputWidget
.prototype.focus = function () {
14974 this.$input
[ 0 ].focus();
14983 OO
.ui
.InputWidget
.prototype.blur = function () {
14984 this.$input
[ 0 ].blur();
14991 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
14992 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
14993 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
14994 this.setValue( state
.value
);
14996 if ( state
.focus
) {
15002 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
15003 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
15004 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
15005 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
15006 * [OOjs UI documentation on MediaWiki] [1] for more information.
15009 * // A ButtonInputWidget rendered as an HTML button, the default.
15010 * var button = new OO.ui.ButtonInputWidget( {
15011 * label: 'Input button',
15015 * $( 'body' ).append( button.$element );
15017 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
15020 * @extends OO.ui.InputWidget
15021 * @mixins OO.ui.mixin.ButtonElement
15022 * @mixins OO.ui.mixin.IconElement
15023 * @mixins OO.ui.mixin.IndicatorElement
15024 * @mixins OO.ui.mixin.LabelElement
15025 * @mixins OO.ui.mixin.TitledElement
15028 * @param {Object} [config] Configuration options
15029 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
15030 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
15031 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
15032 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
15033 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
15035 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
15036 // Configuration initialization
15037 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
15039 // Properties (must be set before parent constructor, which calls #setValue)
15040 this.useInputTag
= config
.useInputTag
;
15042 // Parent constructor
15043 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
15045 // Mixin constructors
15046 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
15047 OO
.ui
.mixin
.IconElement
.call( this, config
);
15048 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
15049 OO
.ui
.mixin
.LabelElement
.call( this, config
);
15050 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
15053 if ( !config
.useInputTag
) {
15054 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
15056 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
15061 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
15062 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
15063 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
15064 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
15065 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
15066 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
15068 /* Static Properties */
15071 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
15072 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
15074 OO
.ui
.ButtonInputWidget
.static.supportsSimpleLabel
= false;
15082 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
15084 // See InputWidget#reusePreInfuseDOM about config.$input
15085 if ( config
.$input
) {
15086 return config
.$input
.empty();
15088 type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ? config
.type
: 'button';
15089 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
15095 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
15097 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
15098 * text, or `null` for no label
15101 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
15102 OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
15104 if ( this.useInputTag
) {
15105 if ( typeof label
=== 'function' ) {
15106 label
= OO
.ui
.resolveMsg( label
);
15108 if ( label
instanceof jQuery
) {
15109 label
= label
.text();
15114 this.$input
.val( label
);
15121 * Set the value of the input.
15123 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
15124 * they do not support {@link #value values}.
15126 * @param {string} value New value
15129 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
15130 if ( !this.useInputTag
) {
15131 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
15137 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
15138 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
15139 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
15140 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
15142 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15145 * // An example of selected, unselected, and disabled checkbox inputs
15146 * var checkbox1=new OO.ui.CheckboxInputWidget( {
15150 * var checkbox2=new OO.ui.CheckboxInputWidget( {
15153 * var checkbox3=new OO.ui.CheckboxInputWidget( {
15157 * // Create a fieldset layout with fields for each checkbox.
15158 * var fieldset = new OO.ui.FieldsetLayout( {
15159 * label: 'Checkboxes'
15161 * fieldset.addItems( [
15162 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
15163 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
15164 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
15166 * $( 'body' ).append( fieldset.$element );
15168 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15171 * @extends OO.ui.InputWidget
15174 * @param {Object} [config] Configuration options
15175 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
15177 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
15178 // Configuration initialization
15179 config
= config
|| {};
15181 // Parent constructor
15182 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
15186 .addClass( 'oo-ui-checkboxInputWidget' )
15187 // Required for pretty styling in MediaWiki theme
15188 .append( $( '<span>' ) );
15189 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
15194 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
15196 /* Static Methods */
15201 OO
.ui
.CheckboxInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
15202 var state
= OO
.ui
.CheckboxInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
15203 state
.checked
= config
.$input
.prop( 'checked' );
15213 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
15214 return $( '<input type="checkbox" />' );
15220 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
15222 if ( !this.isDisabled() ) {
15223 // Allow the stack to clear so the value will be updated
15224 setTimeout( function () {
15225 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
15231 * Set selection state of this checkbox.
15233 * @param {boolean} state `true` for selected
15236 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
15238 if ( this.selected
!== state
) {
15239 this.selected
= state
;
15240 this.$input
.prop( 'checked', this.selected
);
15241 this.emit( 'change', this.selected
);
15247 * Check if this checkbox is selected.
15249 * @return {boolean} Checkbox is selected
15251 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
15252 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
15253 // it, and we won't know unless they're kind enough to trigger a 'change' event.
15254 var selected
= this.$input
.prop( 'checked' );
15255 if ( this.selected
!== selected
) {
15256 this.setSelected( selected
);
15258 return this.selected
;
15264 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
15265 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
15266 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
15267 this.setSelected( state
.checked
);
15272 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
15273 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15274 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15275 * more information about input widgets.
15277 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
15278 * are no options. If no `value` configuration option is provided, the first option is selected.
15279 * If you need a state representing no value (no option being selected), use a DropdownWidget.
15281 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
15284 * // Example: A DropdownInputWidget with three options
15285 * var dropdownInput = new OO.ui.DropdownInputWidget( {
15287 * { data: 'a', label: 'First' },
15288 * { data: 'b', label: 'Second'},
15289 * { data: 'c', label: 'Third' }
15292 * $( 'body' ).append( dropdownInput.$element );
15294 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15297 * @extends OO.ui.InputWidget
15298 * @mixins OO.ui.mixin.TitledElement
15301 * @param {Object} [config] Configuration options
15302 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15303 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
15305 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
15306 // Configuration initialization
15307 config
= config
|| {};
15309 // Properties (must be done before parent constructor which calls #setDisabled)
15310 this.dropdownWidget
= new OO
.ui
.DropdownWidget( config
.dropdown
);
15312 // Parent constructor
15313 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
15315 // Mixin constructors
15316 OO
.ui
.mixin
.TitledElement
.call( this, config
);
15319 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
15322 this.setOptions( config
.options
|| [] );
15324 .addClass( 'oo-ui-dropdownInputWidget' )
15325 .append( this.dropdownWidget
.$element
);
15330 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
15331 OO
.mixinClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.mixin
.TitledElement
);
15339 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function ( config
) {
15340 // See InputWidget#reusePreInfuseDOM about config.$input
15341 if ( config
.$input
) {
15342 return config
.$input
.addClass( 'oo-ui-element-hidden' );
15344 return $( '<input type="hidden">' );
15348 * Handles menu select events.
15351 * @param {OO.ui.MenuOptionWidget} item Selected menu item
15353 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
15354 this.setValue( item
.getData() );
15360 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
15361 value
= this.cleanUpValue( value
);
15362 this.dropdownWidget
.getMenu().selectItemByData( value
);
15363 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
15370 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
15371 this.dropdownWidget
.setDisabled( state
);
15372 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
15377 * Set the options available for this input.
15379 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15382 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
15384 value
= this.getValue(),
15387 // Rebuild the dropdown menu
15388 this.dropdownWidget
.getMenu()
15390 .addItems( options
.map( function ( opt
) {
15391 var optValue
= widget
.cleanUpValue( opt
.data
);
15392 return new OO
.ui
.MenuOptionWidget( {
15394 label
: opt
.label
!== undefined ? opt
.label
: optValue
15398 // Restore the previous value, or reset to something sensible
15399 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
15400 // Previous value is still available, ensure consistency with the dropdown
15401 this.setValue( value
);
15403 // No longer valid, reset
15404 if ( options
.length
) {
15405 this.setValue( options
[ 0 ].data
);
15415 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
15416 this.dropdownWidget
.getMenu().toggle( true );
15423 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
15424 this.dropdownWidget
.getMenu().toggle( false );
15429 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
15430 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
15431 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
15432 * please see the [OOjs UI documentation on MediaWiki][1].
15434 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15437 * // An example of selected, unselected, and disabled radio inputs
15438 * var radio1 = new OO.ui.RadioInputWidget( {
15442 * var radio2 = new OO.ui.RadioInputWidget( {
15445 * var radio3 = new OO.ui.RadioInputWidget( {
15449 * // Create a fieldset layout with fields for each radio button.
15450 * var fieldset = new OO.ui.FieldsetLayout( {
15451 * label: 'Radio inputs'
15453 * fieldset.addItems( [
15454 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
15455 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
15456 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
15458 * $( 'body' ).append( fieldset.$element );
15460 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15463 * @extends OO.ui.InputWidget
15466 * @param {Object} [config] Configuration options
15467 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
15469 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
15470 // Configuration initialization
15471 config
= config
|| {};
15473 // Parent constructor
15474 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
15478 .addClass( 'oo-ui-radioInputWidget' )
15479 // Required for pretty styling in MediaWiki theme
15480 .append( $( '<span>' ) );
15481 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
15486 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
15488 /* Static Methods */
15493 OO
.ui
.RadioInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
15494 var state
= OO
.ui
.RadioInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
15495 state
.checked
= config
.$input
.prop( 'checked' );
15505 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
15506 return $( '<input type="radio" />' );
15512 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
15513 // RadioInputWidget doesn't track its state.
15517 * Set selection state of this radio button.
15519 * @param {boolean} state `true` for selected
15522 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
15523 // RadioInputWidget doesn't track its state.
15524 this.$input
.prop( 'checked', state
);
15529 * Check if this radio button is selected.
15531 * @return {boolean} Radio is selected
15533 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
15534 return this.$input
.prop( 'checked' );
15540 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
15541 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
15542 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
15543 this.setSelected( state
.checked
);
15548 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
15549 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15550 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15551 * more information about input widgets.
15553 * This and OO.ui.DropdownInputWidget support the same configuration options.
15556 * // Example: A RadioSelectInputWidget with three options
15557 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
15559 * { data: 'a', label: 'First' },
15560 * { data: 'b', label: 'Second'},
15561 * { data: 'c', label: 'Third' }
15564 * $( 'body' ).append( radioSelectInput.$element );
15566 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15569 * @extends OO.ui.InputWidget
15572 * @param {Object} [config] Configuration options
15573 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15575 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
15576 // Configuration initialization
15577 config
= config
|| {};
15579 // Properties (must be done before parent constructor which calls #setDisabled)
15580 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
15582 // Parent constructor
15583 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
15586 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
15589 this.setOptions( config
.options
|| [] );
15591 .addClass( 'oo-ui-radioSelectInputWidget' )
15592 .append( this.radioSelectWidget
.$element
);
15597 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
15599 /* Static Properties */
15601 OO
.ui
.RadioSelectInputWidget
.static.supportsSimpleLabel
= false;
15603 /* Static Methods */
15608 OO
.ui
.RadioSelectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
15609 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
15610 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
15620 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
15621 return $( '<input type="hidden">' );
15625 * Handles menu select events.
15628 * @param {OO.ui.RadioOptionWidget} item Selected menu item
15630 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
15631 this.setValue( item
.getData() );
15637 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
15638 value
= this.cleanUpValue( value
);
15639 this.radioSelectWidget
.selectItemByData( value
);
15640 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
15647 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
15648 this.radioSelectWidget
.setDisabled( state
);
15649 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
15654 * Set the options available for this input.
15656 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15659 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
15661 value
= this.getValue(),
15664 // Rebuild the radioSelect menu
15665 this.radioSelectWidget
15667 .addItems( options
.map( function ( opt
) {
15668 var optValue
= widget
.cleanUpValue( opt
.data
);
15669 return new OO
.ui
.RadioOptionWidget( {
15671 label
: opt
.label
!== undefined ? opt
.label
: optValue
15675 // Restore the previous value, or reset to something sensible
15676 if ( this.radioSelectWidget
.getItemFromData( value
) ) {
15677 // Previous value is still available, ensure consistency with the radioSelect
15678 this.setValue( value
);
15680 // No longer valid, reset
15681 if ( options
.length
) {
15682 this.setValue( options
[ 0 ].data
);
15690 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
15691 * size of the field as well as its presentation. In addition, these widgets can be configured
15692 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
15693 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
15694 * which modifies incoming values rather than validating them.
15695 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
15697 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15700 * // Example of a text input widget
15701 * var textInput = new OO.ui.TextInputWidget( {
15702 * value: 'Text input'
15704 * $( 'body' ).append( textInput.$element );
15706 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15709 * @extends OO.ui.InputWidget
15710 * @mixins OO.ui.mixin.IconElement
15711 * @mixins OO.ui.mixin.IndicatorElement
15712 * @mixins OO.ui.mixin.PendingElement
15713 * @mixins OO.ui.mixin.LabelElement
15716 * @param {Object} [config] Configuration options
15717 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
15718 * 'email' or 'url'. Ignored if `multiline` is true.
15720 * Some values of `type` result in additional behaviors:
15722 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
15723 * empties the text field
15724 * @cfg {string} [placeholder] Placeholder text
15725 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
15726 * instruct the browser to focus this widget.
15727 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
15728 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
15729 * @cfg {boolean} [multiline=false] Allow multiple lines of text
15730 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
15731 * specifies minimum number of rows to display.
15732 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
15733 * Use the #maxRows config to specify a maximum number of displayed rows.
15734 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
15735 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
15736 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
15737 * the value or placeholder text: `'before'` or `'after'`
15738 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
15739 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
15740 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
15741 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
15742 * (the value must contain only numbers); when RegExp, a regular expression that must match the
15743 * value for it to be considered valid; when Function, a function receiving the value as parameter
15744 * that must return true, or promise resolving to true, for it to be considered valid.
15746 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
15747 // Configuration initialization
15748 config
= $.extend( {
15750 labelPosition
: 'after'
15752 if ( config
.type
=== 'search' ) {
15753 if ( config
.icon
=== undefined ) {
15754 config
.icon
= 'search';
15756 // indicator: 'clear' is set dynamically later, depending on value
15758 if ( config
.required
) {
15759 if ( config
.indicator
=== undefined ) {
15760 config
.indicator
= 'required';
15764 // Parent constructor
15765 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
15767 // Mixin constructors
15768 OO
.ui
.mixin
.IconElement
.call( this, config
);
15769 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
15770 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
15771 OO
.ui
.mixin
.LabelElement
.call( this, config
);
15774 this.type
= this.getSaneType( config
);
15775 this.readOnly
= false;
15776 this.multiline
= !!config
.multiline
;
15777 this.autosize
= !!config
.autosize
;
15778 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
15779 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
15780 this.validate
= null;
15781 this.styleHeight
= null;
15782 this.scrollWidth
= null;
15784 // Clone for resizing
15785 if ( this.autosize
) {
15786 this.$clone
= this.$input
15788 .insertAfter( this.$input
)
15789 .attr( 'aria-hidden', 'true' )
15790 .addClass( 'oo-ui-element-hidden' );
15793 this.setValidation( config
.validate
);
15794 this.setLabelPosition( config
.labelPosition
);
15798 keypress
: this.onKeyPress
.bind( this ),
15799 blur
: this.onBlur
.bind( this )
15802 focus
: this.onElementAttach
.bind( this )
15804 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
15805 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
15806 this.on( 'labelChange', this.updatePosition
.bind( this ) );
15807 this.connect( this, {
15808 change
: 'onChange',
15809 disable
: 'onDisable'
15814 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
15815 .append( this.$icon
, this.$indicator
);
15816 this.setReadOnly( !!config
.readOnly
);
15817 this.updateSearchIndicator();
15818 if ( config
.placeholder
) {
15819 this.$input
.attr( 'placeholder', config
.placeholder
);
15821 if ( config
.maxLength
!== undefined ) {
15822 this.$input
.attr( 'maxlength', config
.maxLength
);
15824 if ( config
.autofocus
) {
15825 this.$input
.attr( 'autofocus', 'autofocus' );
15827 if ( config
.required
) {
15828 this.$input
.attr( 'required', 'required' );
15829 this.$input
.attr( 'aria-required', 'true' );
15831 if ( config
.autocomplete
=== false ) {
15832 this.$input
.attr( 'autocomplete', 'off' );
15833 // Turning off autocompletion also disables "form caching" when the user navigates to a
15834 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
15836 beforeunload: function () {
15837 this.$input
.removeAttr( 'autocomplete' );
15839 pageshow: function () {
15840 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
15841 // whole page... it shouldn't hurt, though.
15842 this.$input
.attr( 'autocomplete', 'off' );
15846 if ( this.multiline
&& config
.rows
) {
15847 this.$input
.attr( 'rows', config
.rows
);
15849 if ( this.label
|| config
.autosize
) {
15850 this.installParentChangeDetector();
15856 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
15857 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
15858 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
15859 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
15860 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
15862 /* Static Properties */
15864 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
15869 /* Static Methods */
15874 OO
.ui
.TextInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
15875 var state
= OO
.ui
.TextInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
15876 if ( config
.multiline
) {
15877 state
.scrollTop
= config
.$input
.scrollTop();
15885 * An `enter` event is emitted when the user presses 'enter' inside the text box.
15887 * Not emitted if the input is multiline.
15893 * A `resize` event is emitted when autosize is set and the widget resizes
15901 * Handle icon mouse down events.
15904 * @param {jQuery.Event} e Mouse down event
15907 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
15908 if ( e
.which
=== 1 ) {
15909 this.$input
[ 0 ].focus();
15915 * Handle indicator mouse down events.
15918 * @param {jQuery.Event} e Mouse down event
15921 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
15922 if ( e
.which
=== 1 ) {
15923 if ( this.type
=== 'search' ) {
15924 // Clear the text field
15925 this.setValue( '' );
15927 this.$input
[ 0 ].focus();
15933 * Handle key press events.
15936 * @param {jQuery.Event} e Key press event
15937 * @fires enter If enter key is pressed and input is not multiline
15939 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
15940 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
15941 this.emit( 'enter', e
);
15946 * Handle blur events.
15949 * @param {jQuery.Event} e Blur event
15951 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
15952 this.setValidityFlag();
15956 * Handle element attach events.
15959 * @param {jQuery.Event} e Element attach event
15961 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
15962 // Any previously calculated size is now probably invalid if we reattached elsewhere
15963 this.valCache
= null;
15965 this.positionLabel();
15969 * Handle change events.
15971 * @param {string} value
15974 OO
.ui
.TextInputWidget
.prototype.onChange = function () {
15975 this.updateSearchIndicator();
15976 this.setValidityFlag();
15981 * Handle disable events.
15983 * @param {boolean} disabled Element is disabled
15986 OO
.ui
.TextInputWidget
.prototype.onDisable = function () {
15987 this.updateSearchIndicator();
15991 * Check if the input is {@link #readOnly read-only}.
15993 * @return {boolean}
15995 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
15996 return this.readOnly
;
16000 * Set the {@link #readOnly read-only} state of the input.
16002 * @param {boolean} state Make input read-only
16005 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
16006 this.readOnly
= !!state
;
16007 this.$input
.prop( 'readOnly', this.readOnly
);
16008 this.updateSearchIndicator();
16013 * Support function for making #onElementAttach work across browsers.
16015 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
16016 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
16018 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
16019 * first time that the element gets attached to the documented.
16021 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
16022 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
16023 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
16026 if ( MutationObserver
) {
16027 // The new way. If only it wasn't so ugly.
16029 if ( this.$element
.closest( 'html' ).length
) {
16030 // Widget is attached already, do nothing. This breaks the functionality of this function when
16031 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
16032 // would require observation of the whole document, which would hurt performance of other,
16033 // more important code.
16037 // Find topmost node in the tree
16038 topmostNode
= this.$element
[ 0 ];
16039 while ( topmostNode
.parentNode
) {
16040 topmostNode
= topmostNode
.parentNode
;
16043 // We have no way to detect the $element being attached somewhere without observing the entire
16044 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
16045 // parent node of $element, and instead detect when $element is removed from it (and thus
16046 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
16047 // doesn't get attached, we end up back here and create the parent.
16049 mutationObserver
= new MutationObserver( function ( mutations
) {
16050 var i
, j
, removedNodes
;
16051 for ( i
= 0; i
< mutations
.length
; i
++ ) {
16052 removedNodes
= mutations
[ i
].removedNodes
;
16053 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
16054 if ( removedNodes
[ j
] === topmostNode
) {
16055 setTimeout( onRemove
, 0 );
16062 onRemove = function () {
16063 // If the node was attached somewhere else, report it
16064 if ( widget
.$element
.closest( 'html' ).length
) {
16065 widget
.onElementAttach();
16067 mutationObserver
.disconnect();
16068 widget
.installParentChangeDetector();
16071 // Create a fake parent and observe it
16072 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
16073 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
16075 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
16076 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
16077 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
16082 * Automatically adjust the size of the text input.
16084 * This only affects #multiline inputs that are {@link #autosize autosized}.
16089 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
16090 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
,
16091 idealHeight
, newHeight
, scrollWidth
, property
;
16093 if ( this.multiline
&& this.$input
.val() !== this.valCache
) {
16094 if ( this.autosize
) {
16096 .val( this.$input
.val() )
16097 .attr( 'rows', this.minRows
)
16098 // Set inline height property to 0 to measure scroll height
16099 .css( 'height', 0 );
16101 this.$clone
.removeClass( 'oo-ui-element-hidden' );
16103 this.valCache
= this.$input
.val();
16105 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
16107 // Remove inline height property to measure natural heights
16108 this.$clone
.css( 'height', '' );
16109 innerHeight
= this.$clone
.innerHeight();
16110 outerHeight
= this.$clone
.outerHeight();
16112 // Measure max rows height
16114 .attr( 'rows', this.maxRows
)
16115 .css( 'height', 'auto' )
16117 maxInnerHeight
= this.$clone
.innerHeight();
16119 // Difference between reported innerHeight and scrollHeight with no scrollbars present
16120 // Equals 1 on Blink-based browsers and 0 everywhere else
16121 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
16122 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
16124 this.$clone
.addClass( 'oo-ui-element-hidden' );
16126 // Only apply inline height when expansion beyond natural height is needed
16127 // Use the difference between the inner and outer height as a buffer
16128 newHeight
= idealHeight
> innerHeight
? idealHeight
+ ( outerHeight
- innerHeight
) : '';
16129 if ( newHeight
!== this.styleHeight
) {
16130 this.$input
.css( 'height', newHeight
);
16131 this.styleHeight
= newHeight
;
16132 this.emit( 'resize' );
16135 scrollWidth
= this.$input
[ 0 ].offsetWidth
- this.$input
[ 0 ].clientWidth
;
16136 if ( scrollWidth
!== this.scrollWidth
) {
16137 property
= this.$element
.css( 'direction' ) === 'rtl' ? 'left' : 'right';
16139 this.$label
.css( { right
: '', left
: '' } );
16140 this.$indicator
.css( { right
: '', left
: '' } );
16142 if ( scrollWidth
) {
16143 this.$indicator
.css( property
, scrollWidth
);
16144 if ( this.labelPosition
=== 'after' ) {
16145 this.$label
.css( property
, scrollWidth
);
16149 this.scrollWidth
= scrollWidth
;
16150 this.positionLabel();
16160 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
16161 return config
.multiline
?
16162 $( '<textarea>' ) :
16163 $( '<input type="' + this.getSaneType( config
) + '" />' );
16167 * Get sanitized value for 'type' for given config.
16169 * @param {Object} config Configuration options
16170 * @return {string|null}
16173 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
16174 var type
= [ 'text', 'password', 'search', 'email', 'url' ].indexOf( config
.type
) !== -1 ?
16177 return config
.multiline
? 'multiline' : type
;
16181 * Check if the input supports multiple lines.
16183 * @return {boolean}
16185 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
16186 return !!this.multiline
;
16190 * Check if the input automatically adjusts its size.
16192 * @return {boolean}
16194 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
16195 return !!this.autosize
;
16199 * Focus the input and select a specified range within the text.
16201 * @param {number} from Select from offset
16202 * @param {number} [to] Select to offset, defaults to from
16205 OO
.ui
.TextInputWidget
.prototype.selectRange = function ( from, to
) {
16206 var textRange
, isBackwards
, start
, end
,
16207 input
= this.$input
[ 0 ];
16211 isBackwards
= to
< from;
16212 start
= isBackwards
? to
: from;
16213 end
= isBackwards
? from : to
;
16217 if ( input
.setSelectionRange
) {
16218 input
.setSelectionRange( start
, end
, isBackwards
? 'backward' : 'forward' );
16219 } else if ( input
.createTextRange
) {
16221 textRange
= input
.createTextRange();
16222 textRange
.collapse( true );
16223 textRange
.moveStart( 'character', start
);
16224 textRange
.moveEnd( 'character', end
- start
);
16225 textRange
.select();
16231 * Get an object describing the current selection range in a directional manner
16233 * @return {Object} Object containing 'from' and 'to' offsets
16235 OO
.ui
.TextInputWidget
.prototype.getRange = function () {
16236 var input
= this.$input
[ 0 ],
16237 start
= input
.selectionStart
,
16238 end
= input
.selectionEnd
,
16239 isBackwards
= input
.selectionDirection
=== 'backward';
16242 from: isBackwards
? end
: start
,
16243 to
: isBackwards
? start
: end
16248 * Get the length of the text input value.
16250 * This could differ from the length of #getValue if the
16251 * value gets filtered
16253 * @return {number} Input length
16255 OO
.ui
.TextInputWidget
.prototype.getInputLength = function () {
16256 return this.$input
[ 0 ].value
.length
;
16260 * Focus the input and select the entire text.
16264 OO
.ui
.TextInputWidget
.prototype.select = function () {
16265 return this.selectRange( 0, this.getInputLength() );
16269 * Focus the input and move the cursor to the start.
16273 OO
.ui
.TextInputWidget
.prototype.moveCursorToStart = function () {
16274 return this.selectRange( 0 );
16278 * Focus the input and move the cursor to the end.
16282 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
16283 return this.selectRange( this.getInputLength() );
16287 * Insert new content into the input.
16289 * @param {string} content Content to be inserted
16292 OO
.ui
.TextInputWidget
.prototype.insertContent = function ( content
) {
16294 range
= this.getRange(),
16295 value
= this.getValue();
16297 start
= Math
.min( range
.from, range
.to
);
16298 end
= Math
.max( range
.from, range
.to
);
16300 this.setValue( value
.slice( 0, start
) + content
+ value
.slice( end
) );
16301 this.selectRange( start
+ content
.length
);
16306 * Insert new content either side of a selection.
16308 * @param {string} pre Content to be inserted before the selection
16309 * @param {string} post Content to be inserted after the selection
16312 OO
.ui
.TextInputWidget
.prototype.encapsulateContent = function ( pre
, post
) {
16314 range
= this.getRange(),
16315 offset
= pre
.length
;
16317 start
= Math
.min( range
.from, range
.to
);
16318 end
= Math
.max( range
.from, range
.to
);
16320 this.selectRange( start
).insertContent( pre
);
16321 this.selectRange( offset
+ end
).insertContent( post
);
16323 this.selectRange( offset
+ start
, offset
+ end
);
16328 * Set the validation pattern.
16330 * The validation pattern is either a regular expression, a function, or the symbolic name of a
16331 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
16332 * value must contain only numbers).
16334 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
16335 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
16337 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
16338 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
16339 this.validate
= validate
;
16341 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
16346 * Sets the 'invalid' flag appropriately.
16348 * @param {boolean} [isValid] Optionally override validation result
16350 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
16352 setFlag = function ( valid
) {
16354 widget
.$input
.attr( 'aria-invalid', 'true' );
16356 widget
.$input
.removeAttr( 'aria-invalid' );
16358 widget
.setFlags( { invalid
: !valid
} );
16361 if ( isValid
!== undefined ) {
16362 setFlag( isValid
);
16364 this.getValidity().then( function () {
16373 * Check if a value is valid.
16375 * This method returns a promise that resolves with a boolean `true` if the current value is
16376 * considered valid according to the supplied {@link #validate validation pattern}.
16379 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
16381 OO
.ui
.TextInputWidget
.prototype.isValid = function () {
16384 if ( this.validate
instanceof Function
) {
16385 result
= this.validate( this.getValue() );
16386 if ( $.isFunction( result
.promise
) ) {
16387 return result
.promise();
16389 return $.Deferred().resolve( !!result
).promise();
16392 return $.Deferred().resolve( !!this.getValue().match( this.validate
) ).promise();
16397 * Get the validity of current value.
16399 * This method returns a promise that resolves if the value is valid and rejects if
16400 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
16402 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
16404 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
16405 var result
, promise
;
16407 function rejectOrResolve( valid
) {
16409 return $.Deferred().resolve().promise();
16411 return $.Deferred().reject().promise();
16415 if ( this.validate
instanceof Function
) {
16416 result
= this.validate( this.getValue() );
16418 if ( $.isFunction( result
.promise
) ) {
16419 promise
= $.Deferred();
16421 result
.then( function ( valid
) {
16431 return promise
.promise();
16433 return rejectOrResolve( result
);
16436 return rejectOrResolve( this.getValue().match( this.validate
) );
16441 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
16443 * @param {string} labelPosition Label position, 'before' or 'after'
16446 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
16447 this.labelPosition
= labelPosition
;
16448 this.updatePosition();
16453 * Update the position of the inline label.
16455 * This method is called by #setLabelPosition, and can also be called on its own if
16456 * something causes the label to be mispositioned.
16460 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
16461 var after
= this.labelPosition
=== 'after';
16464 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
16465 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
16467 this.valCache
= null;
16468 this.scrollWidth
= null;
16470 this.positionLabel();
16476 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
16477 * already empty or when it's not editable.
16479 OO
.ui
.TextInputWidget
.prototype.updateSearchIndicator = function () {
16480 if ( this.type
=== 'search' ) {
16481 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
16482 this.setIndicator( null );
16484 this.setIndicator( 'clear' );
16490 * Position the label by setting the correct padding on the input.
16495 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
16496 var after
, rtl
, property
;
16497 // Clear old values
16499 // Clear old values if present
16501 'padding-right': '',
16505 if ( this.label
) {
16506 this.$element
.append( this.$label
);
16508 this.$label
.detach();
16512 after
= this.labelPosition
=== 'after';
16513 rtl
= this.$element
.css( 'direction' ) === 'rtl';
16514 property
= after
=== rtl
? 'padding-left' : 'padding-right';
16516 this.$input
.css( property
, this.$label
.outerWidth( true ) + ( after
? this.scrollWidth
: 0 ) );
16524 OO
.ui
.TextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
16525 OO
.ui
.TextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
16526 if ( state
.scrollTop
!== undefined ) {
16527 this.$input
.scrollTop( state
.scrollTop
);
16532 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
16533 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
16534 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
16536 * - by typing a value in the text input field. If the value exactly matches the value of a menu
16537 * option, that option will appear to be selected.
16538 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
16541 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
16543 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
16546 * // Example: A ComboBoxInputWidget.
16547 * var comboBox = new OO.ui.ComboBoxInputWidget( {
16548 * label: 'ComboBoxInputWidget',
16549 * value: 'Option 1',
16552 * new OO.ui.MenuOptionWidget( {
16553 * data: 'Option 1',
16554 * label: 'Option One'
16556 * new OO.ui.MenuOptionWidget( {
16557 * data: 'Option 2',
16558 * label: 'Option Two'
16560 * new OO.ui.MenuOptionWidget( {
16561 * data: 'Option 3',
16562 * label: 'Option Three'
16564 * new OO.ui.MenuOptionWidget( {
16565 * data: 'Option 4',
16566 * label: 'Option Four'
16568 * new OO.ui.MenuOptionWidget( {
16569 * data: 'Option 5',
16570 * label: 'Option Five'
16575 * $( 'body' ).append( comboBox.$element );
16577 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16580 * @extends OO.ui.TextInputWidget
16583 * @param {Object} [config] Configuration options
16584 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
16585 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
16586 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
16587 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
16588 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
16590 OO
.ui
.ComboBoxInputWidget
= function OoUiComboBoxInputWidget( config
) {
16591 // Configuration initialization
16592 config
= $.extend( {
16595 // For backwards-compatibility with ComboBoxWidget config
16596 $.extend( config
, config
.input
);
16598 // Parent constructor
16599 OO
.ui
.ComboBoxInputWidget
.parent
.call( this, config
);
16602 this.$overlay
= config
.$overlay
|| this.$element
;
16603 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
16607 $container
: this.$element
,
16608 disabled
: this.isDisabled()
16612 // For backwards-compatibility with ComboBoxWidget
16616 this.$indicator
.on( {
16617 click
: this.onIndicatorClick
.bind( this ),
16618 keypress
: this.onIndicatorKeyPress
.bind( this )
16620 this.connect( this, {
16621 change
: 'onInputChange',
16622 enter
: 'onInputEnter'
16624 this.menu
.connect( this, {
16625 choose
: 'onMenuChoose',
16626 add
: 'onMenuItemsChange',
16627 remove
: 'onMenuItemsChange'
16631 this.$input
.attr( {
16633 'aria-autocomplete': 'list'
16635 // Do not override options set via config.menu.items
16636 if ( config
.options
!== undefined ) {
16637 this.setOptions( config
.options
);
16639 // Extra class for backwards-compatibility with ComboBoxWidget
16640 this.$element
.addClass( 'oo-ui-comboBoxInputWidget oo-ui-comboBoxWidget' );
16641 this.$overlay
.append( this.menu
.$element
);
16642 this.onMenuItemsChange();
16647 OO
.inheritClass( OO
.ui
.ComboBoxInputWidget
, OO
.ui
.TextInputWidget
);
16652 * Get the combobox's menu.
16653 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
16655 OO
.ui
.ComboBoxInputWidget
.prototype.getMenu = function () {
16660 * Get the combobox's text input widget.
16661 * @return {OO.ui.TextInputWidget} Text input widget
16663 OO
.ui
.ComboBoxInputWidget
.prototype.getInput = function () {
16668 * Handle input change events.
16671 * @param {string} value New value
16673 OO
.ui
.ComboBoxInputWidget
.prototype.onInputChange = function ( value
) {
16674 var match
= this.menu
.getItemFromData( value
);
16676 this.menu
.selectItem( match
);
16677 if ( this.menu
.getHighlightedItem() ) {
16678 this.menu
.highlightItem( match
);
16681 if ( !this.isDisabled() ) {
16682 this.menu
.toggle( true );
16687 * Handle mouse click events.
16690 * @param {jQuery.Event} e Mouse click event
16692 OO
.ui
.ComboBoxInputWidget
.prototype.onIndicatorClick = function ( e
) {
16693 if ( !this.isDisabled() && e
.which
=== 1 ) {
16694 this.menu
.toggle();
16695 this.$input
[ 0 ].focus();
16701 * Handle key press events.
16704 * @param {jQuery.Event} e Key press event
16706 OO
.ui
.ComboBoxInputWidget
.prototype.onIndicatorKeyPress = function ( e
) {
16707 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
16708 this.menu
.toggle();
16709 this.$input
[ 0 ].focus();
16715 * Handle input enter events.
16719 OO
.ui
.ComboBoxInputWidget
.prototype.onInputEnter = function () {
16720 if ( !this.isDisabled() ) {
16721 this.menu
.toggle( false );
16726 * Handle menu choose events.
16729 * @param {OO.ui.OptionWidget} item Chosen item
16731 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuChoose = function ( item
) {
16732 this.setValue( item
.getData() );
16736 * Handle menu item change events.
16740 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuItemsChange = function () {
16741 var match
= this.menu
.getItemFromData( this.getValue() );
16742 this.menu
.selectItem( match
);
16743 if ( this.menu
.getHighlightedItem() ) {
16744 this.menu
.highlightItem( match
);
16746 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu
.isEmpty() );
16752 OO
.ui
.ComboBoxInputWidget
.prototype.setDisabled = function ( disabled
) {
16754 OO
.ui
.ComboBoxInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
16757 this.menu
.setDisabled( this.isDisabled() );
16764 * Set the options available for this input.
16766 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
16769 OO
.ui
.ComboBoxInputWidget
.prototype.setOptions = function ( options
) {
16772 .addItems( options
.map( function ( opt
) {
16773 return new OO
.ui
.MenuOptionWidget( {
16775 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
16784 * @deprecated Use OO.ui.ComboBoxInputWidget instead.
16786 OO
.ui
.ComboBoxWidget
= OO
.ui
.ComboBoxInputWidget
;
16789 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
16790 * be configured with a `label` option that is set to a string, a label node, or a function:
16792 * - String: a plaintext string
16793 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
16794 * label that includes a link or special styling, such as a gray color or additional graphical elements.
16795 * - Function: a function that will produce a string in the future. Functions are used
16796 * in cases where the value of the label is not currently defined.
16798 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
16799 * will come into focus when the label is clicked.
16802 * // Examples of LabelWidgets
16803 * var label1 = new OO.ui.LabelWidget( {
16804 * label: 'plaintext label'
16806 * var label2 = new OO.ui.LabelWidget( {
16807 * label: $( '<a href="default.html">jQuery label</a>' )
16809 * // Create a fieldset layout with fields for each example
16810 * var fieldset = new OO.ui.FieldsetLayout();
16811 * fieldset.addItems( [
16812 * new OO.ui.FieldLayout( label1 ),
16813 * new OO.ui.FieldLayout( label2 )
16815 * $( 'body' ).append( fieldset.$element );
16818 * @extends OO.ui.Widget
16819 * @mixins OO.ui.mixin.LabelElement
16822 * @param {Object} [config] Configuration options
16823 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
16824 * Clicking the label will focus the specified input field.
16826 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
16827 // Configuration initialization
16828 config
= config
|| {};
16830 // Parent constructor
16831 OO
.ui
.LabelWidget
.parent
.call( this, config
);
16833 // Mixin constructors
16834 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
16835 OO
.ui
.mixin
.TitledElement
.call( this, config
);
16838 this.input
= config
.input
;
16841 if ( this.input
instanceof OO
.ui
.InputWidget
) {
16842 this.$element
.on( 'click', this.onClick
.bind( this ) );
16846 this.$element
.addClass( 'oo-ui-labelWidget' );
16851 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
16852 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
16853 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
16855 /* Static Properties */
16857 OO
.ui
.LabelWidget
.static.tagName
= 'span';
16862 * Handles label mouse click events.
16865 * @param {jQuery.Event} e Mouse click event
16867 OO
.ui
.LabelWidget
.prototype.onClick = function () {
16868 this.input
.simulateLabelClick();
16873 * OptionWidgets are special elements that can be selected and configured with data. The
16874 * data is often unique for each option, but it does not have to be. OptionWidgets are used
16875 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
16876 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
16878 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16881 * @extends OO.ui.Widget
16882 * @mixins OO.ui.mixin.LabelElement
16883 * @mixins OO.ui.mixin.FlaggedElement
16886 * @param {Object} [config] Configuration options
16888 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
16889 // Configuration initialization
16890 config
= config
|| {};
16892 // Parent constructor
16893 OO
.ui
.OptionWidget
.parent
.call( this, config
);
16895 // Mixin constructors
16896 OO
.ui
.mixin
.ItemWidget
.call( this );
16897 OO
.ui
.mixin
.LabelElement
.call( this, config
);
16898 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
16901 this.selected
= false;
16902 this.highlighted
= false;
16903 this.pressed
= false;
16907 .data( 'oo-ui-optionWidget', this )
16908 .attr( 'role', 'option' )
16909 .attr( 'aria-selected', 'false' )
16910 .addClass( 'oo-ui-optionWidget' )
16911 .append( this.$label
);
16916 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
16917 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
16918 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
16919 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
16921 /* Static Properties */
16923 OO
.ui
.OptionWidget
.static.selectable
= true;
16925 OO
.ui
.OptionWidget
.static.highlightable
= true;
16927 OO
.ui
.OptionWidget
.static.pressable
= true;
16929 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
16934 * Check if the option can be selected.
16936 * @return {boolean} Item is selectable
16938 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
16939 return this.constructor.static.selectable
&& !this.isDisabled() && this.isVisible();
16943 * Check if the option can be highlighted. A highlight indicates that the option
16944 * may be selected when a user presses enter or clicks. Disabled items cannot
16947 * @return {boolean} Item is highlightable
16949 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
16950 return this.constructor.static.highlightable
&& !this.isDisabled() && this.isVisible();
16954 * Check if the option can be pressed. The pressed state occurs when a user mouses
16955 * down on an item, but has not yet let go of the mouse.
16957 * @return {boolean} Item is pressable
16959 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
16960 return this.constructor.static.pressable
&& !this.isDisabled() && this.isVisible();
16964 * Check if the option is selected.
16966 * @return {boolean} Item is selected
16968 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
16969 return this.selected
;
16973 * Check if the option is highlighted. A highlight indicates that the
16974 * item may be selected when a user presses enter or clicks.
16976 * @return {boolean} Item is highlighted
16978 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
16979 return this.highlighted
;
16983 * Check if the option is pressed. The pressed state occurs when a user mouses
16984 * down on an item, but has not yet let go of the mouse. The item may appear
16985 * selected, but it will not be selected until the user releases the mouse.
16987 * @return {boolean} Item is pressed
16989 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
16990 return this.pressed
;
16994 * Set the option’s selected state. In general, all modifications to the selection
16995 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
16996 * method instead of this method.
16998 * @param {boolean} [state=false] Select option
17001 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
17002 if ( this.constructor.static.selectable
) {
17003 this.selected
= !!state
;
17005 .toggleClass( 'oo-ui-optionWidget-selected', state
)
17006 .attr( 'aria-selected', state
.toString() );
17007 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
17008 this.scrollElementIntoView();
17010 this.updateThemeClasses();
17016 * Set the option’s highlighted state. In general, all programmatic
17017 * modifications to the highlight should be handled by the
17018 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
17019 * method instead of this method.
17021 * @param {boolean} [state=false] Highlight option
17024 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
17025 if ( this.constructor.static.highlightable
) {
17026 this.highlighted
= !!state
;
17027 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
17028 this.updateThemeClasses();
17034 * Set the option’s pressed state. In general, all
17035 * programmatic modifications to the pressed state should be handled by the
17036 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
17037 * method instead of this method.
17039 * @param {boolean} [state=false] Press option
17042 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
17043 if ( this.constructor.static.pressable
) {
17044 this.pressed
= !!state
;
17045 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
17046 this.updateThemeClasses();
17052 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
17053 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
17054 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
17055 * options. For more information about options and selects, please see the
17056 * [OOjs UI documentation on MediaWiki][1].
17059 * // Decorated options in a select widget
17060 * var select = new OO.ui.SelectWidget( {
17062 * new OO.ui.DecoratedOptionWidget( {
17064 * label: 'Option with icon',
17067 * new OO.ui.DecoratedOptionWidget( {
17069 * label: 'Option with indicator',
17070 * indicator: 'next'
17074 * $( 'body' ).append( select.$element );
17076 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17079 * @extends OO.ui.OptionWidget
17080 * @mixins OO.ui.mixin.IconElement
17081 * @mixins OO.ui.mixin.IndicatorElement
17084 * @param {Object} [config] Configuration options
17086 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
17087 // Parent constructor
17088 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
17090 // Mixin constructors
17091 OO
.ui
.mixin
.IconElement
.call( this, config
);
17092 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
17096 .addClass( 'oo-ui-decoratedOptionWidget' )
17097 .prepend( this.$icon
)
17098 .append( this.$indicator
);
17103 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
17104 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
17105 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
17108 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
17109 * can be selected and configured with data. The class is
17110 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
17111 * [OOjs UI documentation on MediaWiki] [1] for more information.
17113 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
17116 * @extends OO.ui.DecoratedOptionWidget
17117 * @mixins OO.ui.mixin.ButtonElement
17118 * @mixins OO.ui.mixin.TabIndexedElement
17119 * @mixins OO.ui.mixin.TitledElement
17122 * @param {Object} [config] Configuration options
17124 OO
.ui
.ButtonOptionWidget
= function OoUiButtonOptionWidget( config
) {
17125 // Configuration initialization
17126 config
= config
|| {};
17128 // Parent constructor
17129 OO
.ui
.ButtonOptionWidget
.parent
.call( this, config
);
17131 // Mixin constructors
17132 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
17133 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
17134 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, {
17135 $tabIndexed
: this.$button
,
17140 this.$element
.addClass( 'oo-ui-buttonOptionWidget' );
17141 this.$button
.append( this.$element
.contents() );
17142 this.$element
.append( this.$button
);
17147 OO
.inheritClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
17148 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.ButtonElement
);
17149 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.TitledElement
);
17150 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.TabIndexedElement
);
17152 /* Static Properties */
17154 // Allow button mouse down events to pass through so they can be handled by the parent select widget
17155 OO
.ui
.ButtonOptionWidget
.static.cancelButtonMouseDownEvents
= false;
17157 OO
.ui
.ButtonOptionWidget
.static.highlightable
= false;
17164 OO
.ui
.ButtonOptionWidget
.prototype.setSelected = function ( state
) {
17165 OO
.ui
.ButtonOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
17167 if ( this.constructor.static.selectable
) {
17168 this.setActive( state
);
17175 * RadioOptionWidget is an option widget that looks like a radio button.
17176 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
17177 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
17179 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
17182 * @extends OO.ui.OptionWidget
17185 * @param {Object} [config] Configuration options
17187 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
17188 // Configuration initialization
17189 config
= config
|| {};
17191 // Properties (must be done before parent constructor which calls #setDisabled)
17192 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
17194 // Parent constructor
17195 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
17198 this.radio
.$input
.on( 'focus', this.onInputFocus
.bind( this ) );
17201 // Remove implicit role, we're handling it ourselves
17202 this.radio
.$input
.attr( 'role', 'presentation' );
17204 .addClass( 'oo-ui-radioOptionWidget' )
17205 .attr( 'role', 'radio' )
17206 .attr( 'aria-checked', 'false' )
17207 .removeAttr( 'aria-selected' )
17208 .prepend( this.radio
.$element
);
17213 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
17215 /* Static Properties */
17217 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
17219 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
17221 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
17223 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
17228 * @param {jQuery.Event} e Focus event
17231 OO
.ui
.RadioOptionWidget
.prototype.onInputFocus = function () {
17232 this.radio
.$input
.blur();
17233 this.$element
.parent().focus();
17239 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
17240 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
17242 this.radio
.setSelected( state
);
17244 .attr( 'aria-checked', state
.toString() )
17245 .removeAttr( 'aria-selected' );
17253 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
17254 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
17256 this.radio
.setDisabled( this.isDisabled() );
17262 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
17263 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
17264 * the [OOjs UI documentation on MediaWiki] [1] for more information.
17266 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
17269 * @extends OO.ui.DecoratedOptionWidget
17272 * @param {Object} [config] Configuration options
17274 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
17275 // Configuration initialization
17276 config
= $.extend( { icon
: 'check' }, config
);
17278 // Parent constructor
17279 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
17283 .attr( 'role', 'menuitem' )
17284 .addClass( 'oo-ui-menuOptionWidget' );
17289 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
17291 /* Static Properties */
17293 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
17296 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
17297 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
17300 * var myDropdown = new OO.ui.DropdownWidget( {
17303 * new OO.ui.MenuSectionOptionWidget( {
17306 * new OO.ui.MenuOptionWidget( {
17308 * label: 'Welsh Corgi'
17310 * new OO.ui.MenuOptionWidget( {
17312 * label: 'Standard Poodle'
17314 * new OO.ui.MenuSectionOptionWidget( {
17317 * new OO.ui.MenuOptionWidget( {
17324 * $( 'body' ).append( myDropdown.$element );
17327 * @extends OO.ui.DecoratedOptionWidget
17330 * @param {Object} [config] Configuration options
17332 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
17333 // Parent constructor
17334 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
17337 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' );
17342 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
17344 /* Static Properties */
17346 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
17348 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
17351 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
17353 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
17354 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
17358 * @extends OO.ui.DecoratedOptionWidget
17361 * @param {Object} [config] Configuration options
17362 * @cfg {number} [level] Indentation level
17363 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
17365 OO
.ui
.OutlineOptionWidget
= function OoUiOutlineOptionWidget( config
) {
17366 // Configuration initialization
17367 config
= config
|| {};
17369 // Parent constructor
17370 OO
.ui
.OutlineOptionWidget
.parent
.call( this, config
);
17374 this.movable
= !!config
.movable
;
17375 this.removable
= !!config
.removable
;
17378 this.$element
.addClass( 'oo-ui-outlineOptionWidget' );
17379 this.setLevel( config
.level
);
17384 OO
.inheritClass( OO
.ui
.OutlineOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
17386 /* Static Properties */
17388 OO
.ui
.OutlineOptionWidget
.static.highlightable
= false;
17390 OO
.ui
.OutlineOptionWidget
.static.scrollIntoViewOnSelect
= true;
17392 OO
.ui
.OutlineOptionWidget
.static.levelClass
= 'oo-ui-outlineOptionWidget-level-';
17394 OO
.ui
.OutlineOptionWidget
.static.levels
= 3;
17399 * Check if item is movable.
17401 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17403 * @return {boolean} Item is movable
17405 OO
.ui
.OutlineOptionWidget
.prototype.isMovable = function () {
17406 return this.movable
;
17410 * Check if item is removable.
17412 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17414 * @return {boolean} Item is removable
17416 OO
.ui
.OutlineOptionWidget
.prototype.isRemovable = function () {
17417 return this.removable
;
17421 * Get indentation level.
17423 * @return {number} Indentation level
17425 OO
.ui
.OutlineOptionWidget
.prototype.getLevel = function () {
17432 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17434 * @param {boolean} movable Item is movable
17437 OO
.ui
.OutlineOptionWidget
.prototype.setMovable = function ( movable
) {
17438 this.movable
= !!movable
;
17439 this.updateThemeClasses();
17444 * Set removability.
17446 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17448 * @param {boolean} movable Item is removable
17451 OO
.ui
.OutlineOptionWidget
.prototype.setRemovable = function ( removable
) {
17452 this.removable
= !!removable
;
17453 this.updateThemeClasses();
17458 * Set indentation level.
17460 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
17463 OO
.ui
.OutlineOptionWidget
.prototype.setLevel = function ( level
) {
17464 var levels
= this.constructor.static.levels
,
17465 levelClass
= this.constructor.static.levelClass
,
17468 this.level
= level
? Math
.max( 0, Math
.min( levels
- 1, level
) ) : 0;
17470 if ( this.level
=== i
) {
17471 this.$element
.addClass( levelClass
+ i
);
17473 this.$element
.removeClass( levelClass
+ i
);
17476 this.updateThemeClasses();
17482 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
17484 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
17485 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
17489 * @extends OO.ui.OptionWidget
17492 * @param {Object} [config] Configuration options
17494 OO
.ui
.TabOptionWidget
= function OoUiTabOptionWidget( config
) {
17495 // Configuration initialization
17496 config
= config
|| {};
17498 // Parent constructor
17499 OO
.ui
.TabOptionWidget
.parent
.call( this, config
);
17502 this.$element
.addClass( 'oo-ui-tabOptionWidget' );
17507 OO
.inheritClass( OO
.ui
.TabOptionWidget
, OO
.ui
.OptionWidget
);
17509 /* Static Properties */
17511 OO
.ui
.TabOptionWidget
.static.highlightable
= false;
17514 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
17515 * By default, each popup has an anchor that points toward its origin.
17516 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
17519 * // A popup widget.
17520 * var popup = new OO.ui.PopupWidget( {
17521 * $content: $( '<p>Hi there!</p>' ),
17526 * $( 'body' ).append( popup.$element );
17527 * // To display the popup, toggle the visibility to 'true'.
17528 * popup.toggle( true );
17530 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
17533 * @extends OO.ui.Widget
17534 * @mixins OO.ui.mixin.LabelElement
17535 * @mixins OO.ui.mixin.ClippableElement
17538 * @param {Object} [config] Configuration options
17539 * @cfg {number} [width=320] Width of popup in pixels
17540 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
17541 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
17542 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
17543 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
17544 * popup is leaning towards the right of the screen.
17545 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
17546 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
17547 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
17548 * sentence in the given language.
17549 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
17550 * See the [OOjs UI docs on MediaWiki][3] for an example.
17551 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
17552 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
17553 * @cfg {jQuery} [$content] Content to append to the popup's body
17554 * @cfg {jQuery} [$footer] Content to append to the popup's footer
17555 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
17556 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
17557 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
17559 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
17560 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
17562 * @cfg {boolean} [padded] Add padding to the popup's body
17564 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
17565 // Configuration initialization
17566 config
= config
|| {};
17568 // Parent constructor
17569 OO
.ui
.PopupWidget
.parent
.call( this, config
);
17571 // Properties (must be set before ClippableElement constructor call)
17572 this.$body
= $( '<div>' );
17573 this.$popup
= $( '<div>' );
17575 // Mixin constructors
17576 OO
.ui
.mixin
.LabelElement
.call( this, config
);
17577 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, {
17578 $clippable
: this.$body
,
17579 $clippableContainer
: this.$popup
17583 this.$head
= $( '<div>' );
17584 this.$footer
= $( '<div>' );
17585 this.$anchor
= $( '<div>' );
17586 // If undefined, will be computed lazily in updateDimensions()
17587 this.$container
= config
.$container
;
17588 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
17589 this.autoClose
= !!config
.autoClose
;
17590 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
17591 this.transitionTimeout
= null;
17592 this.anchor
= null;
17593 this.width
= config
.width
!== undefined ? config
.width
: 320;
17594 this.height
= config
.height
!== undefined ? config
.height
: null;
17595 this.setAlignment( config
.align
);
17596 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
17597 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
17598 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
17601 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
17604 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
17605 this.$body
.addClass( 'oo-ui-popupWidget-body' );
17606 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
17608 .addClass( 'oo-ui-popupWidget-head' )
17609 .append( this.$label
, this.closeButton
.$element
);
17610 this.$footer
.addClass( 'oo-ui-popupWidget-footer' );
17611 if ( !config
.head
) {
17612 this.$head
.addClass( 'oo-ui-element-hidden' );
17614 if ( !config
.$footer
) {
17615 this.$footer
.addClass( 'oo-ui-element-hidden' );
17618 .addClass( 'oo-ui-popupWidget-popup' )
17619 .append( this.$head
, this.$body
, this.$footer
);
17621 .addClass( 'oo-ui-popupWidget' )
17622 .append( this.$popup
, this.$anchor
);
17623 // Move content, which was added to #$element by OO.ui.Widget, to the body
17624 if ( config
.$content
instanceof jQuery
) {
17625 this.$body
.append( config
.$content
);
17627 if ( config
.$footer
instanceof jQuery
) {
17628 this.$footer
.append( config
.$footer
);
17630 if ( config
.padded
) {
17631 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
17634 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
17635 // that reference properties not initialized at that time of parent class construction
17636 // TODO: Find a better way to handle post-constructor setup
17637 this.visible
= false;
17638 this.$element
.addClass( 'oo-ui-element-hidden' );
17643 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
17644 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
17645 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
17650 * Handles mouse down events.
17653 * @param {MouseEvent} e Mouse down event
17655 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
17657 this.isVisible() &&
17658 !$.contains( this.$element
[ 0 ], e
.target
) &&
17659 ( !this.$autoCloseIgnore
|| !this.$autoCloseIgnore
.has( e
.target
).length
)
17661 this.toggle( false );
17666 * Bind mouse down listener.
17670 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
17671 // Capture clicks outside popup
17672 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler
);
17676 * Handles close button click events.
17680 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
17681 if ( this.isVisible() ) {
17682 this.toggle( false );
17687 * Unbind mouse down listener.
17691 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
17692 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler
);
17696 * Handles key down events.
17699 * @param {KeyboardEvent} e Key down event
17701 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
17703 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
17706 this.toggle( false );
17707 e
.preventDefault();
17708 e
.stopPropagation();
17713 * Bind key down listener.
17717 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
17718 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler
);
17722 * Unbind key down listener.
17726 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
17727 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler
);
17731 * Show, hide, or toggle the visibility of the anchor.
17733 * @param {boolean} [show] Show anchor, omit to toggle
17735 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
17736 show
= show
=== undefined ? !this.anchored
: !!show
;
17738 if ( this.anchored
!== show
) {
17740 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
17742 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
17744 this.anchored
= show
;
17749 * Check if the anchor is visible.
17751 * @return {boolean} Anchor is visible
17753 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
17754 return this.anchor
;
17760 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
17762 show
= show
=== undefined ? !this.isVisible() : !!show
;
17764 change
= show
!== this.isVisible();
17767 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
17771 if ( this.autoClose
) {
17772 this.bindMouseDownListener();
17773 this.bindKeyDownListener();
17775 this.updateDimensions();
17776 this.toggleClipping( true );
17778 this.toggleClipping( false );
17779 if ( this.autoClose
) {
17780 this.unbindMouseDownListener();
17781 this.unbindKeyDownListener();
17790 * Set the size of the popup.
17792 * Changing the size may also change the popup's position depending on the alignment.
17794 * @param {number} width Width in pixels
17795 * @param {number} height Height in pixels
17796 * @param {boolean} [transition=false] Use a smooth transition
17799 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
17800 this.width
= width
;
17801 this.height
= height
!== undefined ? height
: null;
17802 if ( this.isVisible() ) {
17803 this.updateDimensions( transition
);
17808 * Update the size and position.
17810 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
17811 * be called automatically.
17813 * @param {boolean} [transition=false] Use a smooth transition
17816 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
17817 var popupOffset
, originOffset
, containerLeft
, containerWidth
, containerRight
,
17818 popupLeft
, popupRight
, overlapLeft
, overlapRight
, anchorWidth
,
17819 align
= this.align
,
17822 if ( !this.$container
) {
17823 // Lazy-initialize $container if not specified in constructor
17824 this.$container
= $( this.getClosestScrollableElementContainer() );
17827 // Set height and width before measuring things, since it might cause our measurements
17828 // to change (e.g. due to scrollbars appearing or disappearing)
17831 height
: this.height
!== null ? this.height
: 'auto'
17834 // If we are in RTL, we need to flip the alignment, unless it is center
17835 if ( align
=== 'forwards' || align
=== 'backwards' ) {
17836 if ( this.$container
.css( 'direction' ) === 'rtl' ) {
17837 align
= ( { forwards
: 'force-left', backwards
: 'force-right' } )[ this.align
];
17839 align
= ( { forwards
: 'force-right', backwards
: 'force-left' } )[ this.align
];
17844 // Compute initial popupOffset based on alignment
17845 popupOffset
= this.width
* ( { 'force-left': -1, center
: -0.5, 'force-right': 0 } )[ align
];
17847 // Figure out if this will cause the popup to go beyond the edge of the container
17848 originOffset
= this.$element
.offset().left
;
17849 containerLeft
= this.$container
.offset().left
;
17850 containerWidth
= this.$container
.innerWidth();
17851 containerRight
= containerLeft
+ containerWidth
;
17852 popupLeft
= popupOffset
- this.containerPadding
;
17853 popupRight
= popupOffset
+ this.containerPadding
+ this.width
+ this.containerPadding
;
17854 overlapLeft
= ( originOffset
+ popupLeft
) - containerLeft
;
17855 overlapRight
= containerRight
- ( originOffset
+ popupRight
);
17857 // Adjust offset to make the popup not go beyond the edge, if needed
17858 if ( overlapRight
< 0 ) {
17859 popupOffset
+= overlapRight
;
17860 } else if ( overlapLeft
< 0 ) {
17861 popupOffset
-= overlapLeft
;
17864 // Adjust offset to avoid anchor being rendered too close to the edge
17865 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
17866 // TODO: Find a measurement that works for CSS anchors and image anchors
17867 anchorWidth
= this.$anchor
[ 0 ].scrollWidth
* 2;
17868 if ( popupOffset
+ this.width
< anchorWidth
) {
17869 popupOffset
= anchorWidth
- this.width
;
17870 } else if ( -popupOffset
< anchorWidth
) {
17871 popupOffset
= -anchorWidth
;
17874 // Prevent transition from being interrupted
17875 clearTimeout( this.transitionTimeout
);
17876 if ( transition
) {
17877 // Enable transition
17878 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
17881 // Position body relative to anchor
17882 this.$popup
.css( 'margin-left', popupOffset
);
17884 if ( transition
) {
17885 // Prevent transitioning after transition is complete
17886 this.transitionTimeout
= setTimeout( function () {
17887 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
17890 // Prevent transitioning immediately
17891 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
17894 // Reevaluate clipping state since we've relocated and resized the popup
17901 * Set popup alignment
17902 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17903 * `backwards` or `forwards`.
17905 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
17906 // Validate alignment and transform deprecated values
17907 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
17908 this.align
= { left
: 'force-right', right
: 'force-left' }[ align
] || align
;
17910 this.align
= 'center';
17915 * Get popup alignment
17916 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17917 * `backwards` or `forwards`.
17919 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
17924 * Progress bars visually display the status of an operation, such as a download,
17925 * and can be either determinate or indeterminate:
17927 * - **determinate** process bars show the percent of an operation that is complete.
17929 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
17930 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
17931 * not use percentages.
17933 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
17936 * // Examples of determinate and indeterminate progress bars.
17937 * var progressBar1 = new OO.ui.ProgressBarWidget( {
17940 * var progressBar2 = new OO.ui.ProgressBarWidget();
17942 * // Create a FieldsetLayout to layout progress bars
17943 * var fieldset = new OO.ui.FieldsetLayout;
17944 * fieldset.addItems( [
17945 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
17946 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
17948 * $( 'body' ).append( fieldset.$element );
17951 * @extends OO.ui.Widget
17954 * @param {Object} [config] Configuration options
17955 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
17956 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
17957 * By default, the progress bar is indeterminate.
17959 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
17960 // Configuration initialization
17961 config
= config
|| {};
17963 // Parent constructor
17964 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
17967 this.$bar
= $( '<div>' );
17968 this.progress
= null;
17971 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
17972 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
17975 role
: 'progressbar',
17976 'aria-valuemin': 0,
17977 'aria-valuemax': 100
17979 .addClass( 'oo-ui-progressBarWidget' )
17980 .append( this.$bar
);
17985 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
17987 /* Static Properties */
17989 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
17994 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
17996 * @return {number|boolean} Progress percent
17998 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
17999 return this.progress
;
18003 * Set the percent of the process completed or `false` for an indeterminate process.
18005 * @param {number|boolean} progress Progress percent or `false` for indeterminate
18007 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
18008 this.progress
= progress
;
18010 if ( progress
!== false ) {
18011 this.$bar
.css( 'width', this.progress
+ '%' );
18012 this.$element
.attr( 'aria-valuenow', this.progress
);
18014 this.$bar
.css( 'width', '' );
18015 this.$element
.removeAttr( 'aria-valuenow' );
18017 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress
);
18021 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
18022 * and a menu of search results, which is displayed beneath the query
18023 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
18024 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
18025 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
18027 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
18028 * the [OOjs UI demos][1] for an example.
18030 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
18033 * @extends OO.ui.Widget
18036 * @param {Object} [config] Configuration options
18037 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
18038 * @cfg {string} [value] Initial query value
18040 OO
.ui
.SearchWidget
= function OoUiSearchWidget( config
) {
18041 // Configuration initialization
18042 config
= config
|| {};
18044 // Parent constructor
18045 OO
.ui
.SearchWidget
.parent
.call( this, config
);
18048 this.query
= new OO
.ui
.TextInputWidget( {
18050 placeholder
: config
.placeholder
,
18051 value
: config
.value
18053 this.results
= new OO
.ui
.SelectWidget();
18054 this.$query
= $( '<div>' );
18055 this.$results
= $( '<div>' );
18058 this.query
.connect( this, {
18059 change
: 'onQueryChange',
18060 enter
: 'onQueryEnter'
18062 this.query
.$input
.on( 'keydown', this.onQueryKeydown
.bind( this ) );
18066 .addClass( 'oo-ui-searchWidget-query' )
18067 .append( this.query
.$element
);
18069 .addClass( 'oo-ui-searchWidget-results' )
18070 .append( this.results
.$element
);
18072 .addClass( 'oo-ui-searchWidget' )
18073 .append( this.$results
, this.$query
);
18078 OO
.inheritClass( OO
.ui
.SearchWidget
, OO
.ui
.Widget
);
18083 * Handle query key down events.
18086 * @param {jQuery.Event} e Key down event
18088 OO
.ui
.SearchWidget
.prototype.onQueryKeydown = function ( e
) {
18089 var highlightedItem
, nextItem
,
18090 dir
= e
.which
=== OO
.ui
.Keys
.DOWN
? 1 : ( e
.which
=== OO
.ui
.Keys
.UP
? -1 : 0 );
18093 highlightedItem
= this.results
.getHighlightedItem();
18094 if ( !highlightedItem
) {
18095 highlightedItem
= this.results
.getSelectedItem();
18097 nextItem
= this.results
.getRelativeSelectableItem( highlightedItem
, dir
);
18098 this.results
.highlightItem( nextItem
);
18099 nextItem
.scrollElementIntoView();
18104 * Handle select widget select events.
18106 * Clears existing results. Subclasses should repopulate items according to new query.
18109 * @param {string} value New value
18111 OO
.ui
.SearchWidget
.prototype.onQueryChange = function () {
18113 this.results
.clearItems();
18117 * Handle select widget enter key events.
18119 * Chooses highlighted item.
18122 * @param {string} value New value
18124 OO
.ui
.SearchWidget
.prototype.onQueryEnter = function () {
18125 var highlightedItem
= this.results
.getHighlightedItem();
18126 if ( highlightedItem
) {
18127 this.results
.chooseItem( highlightedItem
);
18132 * Get the query input.
18134 * @return {OO.ui.TextInputWidget} Query input
18136 OO
.ui
.SearchWidget
.prototype.getQuery = function () {
18141 * Get the search results menu.
18143 * @return {OO.ui.SelectWidget} Menu of search results
18145 OO
.ui
.SearchWidget
.prototype.getResults = function () {
18146 return this.results
;
18150 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
18151 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
18152 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
18155 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
18156 * information, please see the [OOjs UI documentation on MediaWiki][1].
18159 * // Example of a select widget with three options
18160 * var select = new OO.ui.SelectWidget( {
18162 * new OO.ui.OptionWidget( {
18164 * label: 'Option One',
18166 * new OO.ui.OptionWidget( {
18168 * label: 'Option Two',
18170 * new OO.ui.OptionWidget( {
18172 * label: 'Option Three',
18176 * $( 'body' ).append( select.$element );
18178 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18182 * @extends OO.ui.Widget
18183 * @mixins OO.ui.mixin.GroupWidget
18186 * @param {Object} [config] Configuration options
18187 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
18188 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
18189 * the [OOjs UI documentation on MediaWiki] [2] for examples.
18190 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18192 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
18193 // Configuration initialization
18194 config
= config
|| {};
18196 // Parent constructor
18197 OO
.ui
.SelectWidget
.parent
.call( this, config
);
18199 // Mixin constructors
18200 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
18203 this.pressed
= false;
18204 this.selecting
= null;
18205 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
18206 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
18207 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
18208 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
18209 this.keyPressBuffer
= '';
18210 this.keyPressBufferTimer
= null;
18213 this.connect( this, {
18216 this.$element
.on( {
18217 mousedown
: this.onMouseDown
.bind( this ),
18218 mouseover
: this.onMouseOver
.bind( this ),
18219 mouseleave
: this.onMouseLeave
.bind( this )
18224 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
18225 .attr( 'role', 'listbox' );
18226 if ( Array
.isArray( config
.items
) ) {
18227 this.addItems( config
.items
);
18233 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
18235 // Need to mixin base class as well
18236 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupElement
);
18237 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
18240 OO
.ui
.SelectWidget
.static.passAllFilter = function () {
18249 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
18251 * @param {OO.ui.OptionWidget|null} item Highlighted item
18257 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
18258 * pressed state of an option.
18260 * @param {OO.ui.OptionWidget|null} item Pressed item
18266 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
18268 * @param {OO.ui.OptionWidget|null} item Selected item
18273 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
18274 * @param {OO.ui.OptionWidget} item Chosen item
18280 * An `add` event is emitted when options are added to the select with the #addItems method.
18282 * @param {OO.ui.OptionWidget[]} items Added items
18283 * @param {number} index Index of insertion point
18289 * A `remove` event is emitted when options are removed from the select with the #clearItems
18290 * or #removeItems methods.
18292 * @param {OO.ui.OptionWidget[]} items Removed items
18298 * Handle mouse down events.
18301 * @param {jQuery.Event} e Mouse down event
18303 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
18306 if ( !this.isDisabled() && e
.which
=== 1 ) {
18307 this.togglePressed( true );
18308 item
= this.getTargetItem( e
);
18309 if ( item
&& item
.isSelectable() ) {
18310 this.pressItem( item
);
18311 this.selecting
= item
;
18312 OO
.ui
.addCaptureEventListener(
18313 this.getElementDocument(),
18315 this.onMouseUpHandler
18317 OO
.ui
.addCaptureEventListener(
18318 this.getElementDocument(),
18320 this.onMouseMoveHandler
18328 * Handle mouse up events.
18331 * @param {jQuery.Event} e Mouse up event
18333 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
18336 this.togglePressed( false );
18337 if ( !this.selecting
) {
18338 item
= this.getTargetItem( e
);
18339 if ( item
&& item
.isSelectable() ) {
18340 this.selecting
= item
;
18343 if ( !this.isDisabled() && e
.which
=== 1 && this.selecting
) {
18344 this.pressItem( null );
18345 this.chooseItem( this.selecting
);
18346 this.selecting
= null;
18349 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup',
18350 this.onMouseUpHandler
);
18351 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mousemove',
18352 this.onMouseMoveHandler
);
18358 * Handle mouse move events.
18361 * @param {jQuery.Event} e Mouse move event
18363 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
18366 if ( !this.isDisabled() && this.pressed
) {
18367 item
= this.getTargetItem( e
);
18368 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
18369 this.pressItem( item
);
18370 this.selecting
= item
;
18377 * Handle mouse over events.
18380 * @param {jQuery.Event} e Mouse over event
18382 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
18385 if ( !this.isDisabled() ) {
18386 item
= this.getTargetItem( e
);
18387 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
18393 * Handle mouse leave events.
18396 * @param {jQuery.Event} e Mouse over event
18398 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
18399 if ( !this.isDisabled() ) {
18400 this.highlightItem( null );
18406 * Handle key down events.
18409 * @param {jQuery.Event} e Key down event
18411 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
18414 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
18416 if ( !this.isDisabled() && this.isVisible() ) {
18417 switch ( e
.keyCode
) {
18418 case OO
.ui
.Keys
.ENTER
:
18419 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
18420 // Was only highlighted, now let's select it. No-op if already selected.
18421 this.chooseItem( currentItem
);
18425 case OO
.ui
.Keys
.UP
:
18426 case OO
.ui
.Keys
.LEFT
:
18427 this.clearKeyPressBuffer();
18428 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
18431 case OO
.ui
.Keys
.DOWN
:
18432 case OO
.ui
.Keys
.RIGHT
:
18433 this.clearKeyPressBuffer();
18434 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
18437 case OO
.ui
.Keys
.ESCAPE
:
18438 case OO
.ui
.Keys
.TAB
:
18439 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
18440 currentItem
.setHighlighted( false );
18442 this.unbindKeyDownListener();
18443 this.unbindKeyPressListener();
18444 // Don't prevent tabbing away / defocusing
18450 if ( nextItem
.constructor.static.highlightable
) {
18451 this.highlightItem( nextItem
);
18453 this.chooseItem( nextItem
);
18455 nextItem
.scrollElementIntoView();
18459 // Can't just return false, because e is not always a jQuery event
18460 e
.preventDefault();
18461 e
.stopPropagation();
18467 * Bind key down listener.
18471 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
18472 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler
);
18476 * Unbind key down listener.
18480 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
18481 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler
);
18485 * Clear the key-press buffer
18489 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
18490 if ( this.keyPressBufferTimer
) {
18491 clearTimeout( this.keyPressBufferTimer
);
18492 this.keyPressBufferTimer
= null;
18494 this.keyPressBuffer
= '';
18498 * Handle key press events.
18501 * @param {jQuery.Event} e Key press event
18503 OO
.ui
.SelectWidget
.prototype.onKeyPress = function ( e
) {
18504 var c
, filter
, item
;
18506 if ( !e
.charCode
) {
18507 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
18508 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
18513 if ( String
.fromCodePoint
) {
18514 c
= String
.fromCodePoint( e
.charCode
);
18516 c
= String
.fromCharCode( e
.charCode
);
18519 if ( this.keyPressBufferTimer
) {
18520 clearTimeout( this.keyPressBufferTimer
);
18522 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
18524 item
= this.getHighlightedItem() || this.getSelectedItem();
18526 if ( this.keyPressBuffer
=== c
) {
18527 // Common (if weird) special case: typing "xxxx" will cycle through all
18528 // the items beginning with "x".
18530 item
= this.getRelativeSelectableItem( item
, 1 );
18533 this.keyPressBuffer
+= c
;
18536 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
18537 if ( !item
|| !filter( item
) ) {
18538 item
= this.getRelativeSelectableItem( item
, 1, filter
);
18541 if ( item
.constructor.static.highlightable
) {
18542 this.highlightItem( item
);
18544 this.chooseItem( item
);
18546 item
.scrollElementIntoView();
18553 * Get a matcher for the specific string
18556 * @param {string} s String to match against items
18557 * @param {boolean} [exact=false] Only accept exact matches
18558 * @return {Function} function ( OO.ui.OptionItem ) => boolean
18560 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
, exact
) {
18563 if ( s
.normalize
) {
18566 s
= exact
? s
.trim() : s
.replace( /^\s+/, '' );
18567 re
= '^\\s*' + s
.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
18571 re
= new RegExp( re
, 'i' );
18572 return function ( item
) {
18573 var l
= item
.getLabel();
18574 if ( typeof l
!== 'string' ) {
18575 l
= item
.$label
.text();
18577 if ( l
.normalize
) {
18580 return re
.test( l
);
18585 * Bind key press listener.
18589 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
18590 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler
);
18594 * Unbind key down listener.
18596 * If you override this, be sure to call this.clearKeyPressBuffer() from your
18601 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
18602 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler
);
18603 this.clearKeyPressBuffer();
18607 * Visibility change handler
18610 * @param {boolean} visible
18612 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
18614 this.clearKeyPressBuffer();
18619 * Get the closest item to a jQuery.Event.
18622 * @param {jQuery.Event} e
18623 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
18625 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
18626 return $( e
.target
).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
18630 * Get selected item.
18632 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
18634 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
18637 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18638 if ( this.items
[ i
].isSelected() ) {
18639 return this.items
[ i
];
18646 * Get highlighted item.
18648 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
18650 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
18653 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18654 if ( this.items
[ i
].isHighlighted() ) {
18655 return this.items
[ i
];
18662 * Toggle pressed state.
18664 * Press is a state that occurs when a user mouses down on an item, but
18665 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
18666 * until the user releases the mouse.
18668 * @param {boolean} pressed An option is being pressed
18670 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
18671 if ( pressed
=== undefined ) {
18672 pressed
= !this.pressed
;
18674 if ( pressed
!== this.pressed
) {
18676 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
18677 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
18678 this.pressed
= pressed
;
18683 * Highlight an option. If the `item` param is omitted, no options will be highlighted
18684 * and any existing highlight will be removed. The highlight is mutually exclusive.
18686 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
18690 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
18691 var i
, len
, highlighted
,
18694 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18695 highlighted
= this.items
[ i
] === item
;
18696 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
18697 this.items
[ i
].setHighlighted( highlighted
);
18702 this.emit( 'highlight', item
);
18709 * Fetch an item by its label.
18711 * @param {string} label Label of the item to select.
18712 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18713 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
18715 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
18716 var i
, item
, found
,
18717 len
= this.items
.length
,
18718 filter
= this.getItemMatcher( label
, true );
18720 for ( i
= 0; i
< len
; i
++ ) {
18721 item
= this.items
[ i
];
18722 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
18729 filter
= this.getItemMatcher( label
, false );
18730 for ( i
= 0; i
< len
; i
++ ) {
18731 item
= this.items
[ i
];
18732 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
18748 * Programmatically select an option by its label. If the item does not exist,
18749 * all options will be deselected.
18751 * @param {string} [label] Label of the item to select.
18752 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18756 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
18757 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
18758 if ( label
=== undefined || !itemFromLabel
) {
18759 return this.selectItem();
18761 return this.selectItem( itemFromLabel
);
18765 * Programmatically select an option by its data. If the `data` parameter is omitted,
18766 * or if the item does not exist, all options will be deselected.
18768 * @param {Object|string} [data] Value of the item to select, omit to deselect all
18772 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
18773 var itemFromData
= this.getItemFromData( data
);
18774 if ( data
=== undefined || !itemFromData
) {
18775 return this.selectItem();
18777 return this.selectItem( itemFromData
);
18781 * Programmatically select an option by its reference. If the `item` parameter is omitted,
18782 * all options will be deselected.
18784 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
18788 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
18789 var i
, len
, selected
,
18792 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18793 selected
= this.items
[ i
] === item
;
18794 if ( this.items
[ i
].isSelected() !== selected
) {
18795 this.items
[ i
].setSelected( selected
);
18800 this.emit( 'select', item
);
18809 * Press is a state that occurs when a user mouses down on an item, but has not
18810 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
18811 * releases the mouse.
18813 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
18817 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
18818 var i
, len
, pressed
,
18821 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18822 pressed
= this.items
[ i
] === item
;
18823 if ( this.items
[ i
].isPressed() !== pressed
) {
18824 this.items
[ i
].setPressed( pressed
);
18829 this.emit( 'press', item
);
18838 * Note that ‘choose’ should never be modified programmatically. A user can choose
18839 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
18840 * use the #selectItem method.
18842 * This method is identical to #selectItem, but may vary in subclasses that take additional action
18843 * when users choose an item with the keyboard or mouse.
18845 * @param {OO.ui.OptionWidget} item Item to choose
18849 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
18851 this.selectItem( item
);
18852 this.emit( 'choose', item
);
18859 * Get an option by its position relative to the specified item (or to the start of the option array,
18860 * if item is `null`). The direction in which to search through the option array is specified with a
18861 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
18862 * `null` if there are no options in the array.
18864 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
18865 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
18866 * @param {Function} filter Only consider items for which this function returns
18867 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
18868 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
18870 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
, filter
) {
18871 var currentIndex
, nextIndex
, i
,
18872 increase
= direction
> 0 ? 1 : -1,
18873 len
= this.items
.length
;
18875 if ( !$.isFunction( filter
) ) {
18876 filter
= OO
.ui
.SelectWidget
.static.passAllFilter
;
18879 if ( item
instanceof OO
.ui
.OptionWidget
) {
18880 currentIndex
= this.items
.indexOf( item
);
18881 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
18883 // If no item is selected and moving forward, start at the beginning.
18884 // If moving backward, start at the end.
18885 nextIndex
= direction
> 0 ? 0 : len
- 1;
18888 for ( i
= 0; i
< len
; i
++ ) {
18889 item
= this.items
[ nextIndex
];
18890 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
18893 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
18899 * Get the next selectable item or `null` if there are no selectable items.
18900 * Disabled options and menu-section markers and breaks are not selectable.
18902 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
18904 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
18907 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18908 item
= this.items
[ i
];
18909 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() ) {
18918 * Add an array of options to the select. Optionally, an index number can be used to
18919 * specify an insertion point.
18921 * @param {OO.ui.OptionWidget[]} items Items to add
18922 * @param {number} [index] Index to insert items after
18926 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
18928 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
18930 // Always provide an index, even if it was omitted
18931 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
18937 * Remove the specified array of options from the select. Options will be detached
18938 * from the DOM, not removed, so they can be reused later. To remove all options from
18939 * the select, you may wish to use the #clearItems method instead.
18941 * @param {OO.ui.OptionWidget[]} items Items to remove
18945 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
18948 // Deselect items being removed
18949 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
18951 if ( item
.isSelected() ) {
18952 this.selectItem( null );
18957 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
18959 this.emit( 'remove', items
);
18965 * Clear all options from the select. Options will be detached from the DOM, not removed,
18966 * so that they can be reused later. To remove a subset of options from the select, use
18967 * the #removeItems method.
18972 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
18973 var items
= this.items
.slice();
18976 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
18979 this.selectItem( null );
18981 this.emit( 'remove', items
);
18987 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
18988 * button options and is used together with
18989 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
18990 * highlighting, choosing, and selecting mutually exclusive options. Please see
18991 * the [OOjs UI documentation on MediaWiki] [1] for more information.
18994 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
18995 * var option1 = new OO.ui.ButtonOptionWidget( {
18997 * label: 'Option 1',
18998 * title: 'Button option 1'
19001 * var option2 = new OO.ui.ButtonOptionWidget( {
19003 * label: 'Option 2',
19004 * title: 'Button option 2'
19007 * var option3 = new OO.ui.ButtonOptionWidget( {
19009 * label: 'Option 3',
19010 * title: 'Button option 3'
19013 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
19014 * items: [ option1, option2, option3 ]
19016 * $( 'body' ).append( buttonSelect.$element );
19018 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
19021 * @extends OO.ui.SelectWidget
19022 * @mixins OO.ui.mixin.TabIndexedElement
19025 * @param {Object} [config] Configuration options
19027 OO
.ui
.ButtonSelectWidget
= function OoUiButtonSelectWidget( config
) {
19028 // Parent constructor
19029 OO
.ui
.ButtonSelectWidget
.parent
.call( this, config
);
19031 // Mixin constructors
19032 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
19035 this.$element
.on( {
19036 focus
: this.bindKeyDownListener
.bind( this ),
19037 blur
: this.unbindKeyDownListener
.bind( this )
19041 this.$element
.addClass( 'oo-ui-buttonSelectWidget' );
19046 OO
.inheritClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.SelectWidget
);
19047 OO
.mixinClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
19050 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
19051 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
19052 * an interface for adding, removing and selecting options.
19053 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
19055 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
19056 * OO.ui.RadioSelectInputWidget instead.
19059 * // A RadioSelectWidget with RadioOptions.
19060 * var option1 = new OO.ui.RadioOptionWidget( {
19062 * label: 'Selected radio option'
19065 * var option2 = new OO.ui.RadioOptionWidget( {
19067 * label: 'Unselected radio option'
19070 * var radioSelect=new OO.ui.RadioSelectWidget( {
19071 * items: [ option1, option2 ]
19074 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
19075 * radioSelect.selectItem( option1 );
19077 * $( 'body' ).append( radioSelect.$element );
19079 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
19083 * @extends OO.ui.SelectWidget
19084 * @mixins OO.ui.mixin.TabIndexedElement
19087 * @param {Object} [config] Configuration options
19089 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
19090 // Parent constructor
19091 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
19093 // Mixin constructors
19094 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
19097 this.$element
.on( {
19098 focus
: this.bindKeyDownListener
.bind( this ),
19099 blur
: this.unbindKeyDownListener
.bind( this )
19104 .addClass( 'oo-ui-radioSelectWidget' )
19105 .attr( 'role', 'radiogroup' );
19110 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
19111 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
19114 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
19115 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
19116 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
19117 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
19118 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
19119 * and customized to be opened, closed, and displayed as needed.
19121 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
19122 * mouse outside the menu.
19124 * Menus also have support for keyboard interaction:
19126 * - Enter/Return key: choose and select a menu option
19127 * - Up-arrow key: highlight the previous menu option
19128 * - Down-arrow key: highlight the next menu option
19129 * - Esc key: hide the menu
19131 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
19132 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
19135 * @extends OO.ui.SelectWidget
19136 * @mixins OO.ui.mixin.ClippableElement
19139 * @param {Object} [config] Configuration options
19140 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
19141 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
19142 * and {@link OO.ui.mixin.LookupElement LookupElement}
19143 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
19144 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiSelectWidget CapsuleMultiSelectWidget}
19145 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
19146 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
19147 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
19148 * that button, unless the button (or its parent widget) is passed in here.
19149 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
19150 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
19152 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
19153 // Configuration initialization
19154 config
= config
|| {};
19156 // Parent constructor
19157 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
19159 // Mixin constructors
19160 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
19163 this.newItems
= null;
19164 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
19165 this.filterFromInput
= !!config
.filterFromInput
;
19166 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
19167 this.$widget
= config
.widget
? config
.widget
.$element
: null;
19168 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
19169 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
19173 .addClass( 'oo-ui-menuSelectWidget' )
19174 .attr( 'role', 'menu' );
19176 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
19177 // that reference properties not initialized at that time of parent class construction
19178 // TODO: Find a better way to handle post-constructor setup
19179 this.visible
= false;
19180 this.$element
.addClass( 'oo-ui-element-hidden' );
19185 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
19186 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
19191 * Handles document mouse down events.
19194 * @param {jQuery.Event} e Key down event
19196 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
19198 !OO
.ui
.contains( this.$element
[ 0 ], e
.target
, true ) &&
19199 ( !this.$widget
|| !OO
.ui
.contains( this.$widget
[ 0 ], e
.target
, true ) )
19201 this.toggle( false );
19208 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
19209 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
19211 if ( !this.isDisabled() && this.isVisible() ) {
19212 switch ( e
.keyCode
) {
19213 case OO
.ui
.Keys
.LEFT
:
19214 case OO
.ui
.Keys
.RIGHT
:
19215 // Do nothing if a text field is associated, arrow keys will be handled natively
19216 if ( !this.$input
) {
19217 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
19220 case OO
.ui
.Keys
.ESCAPE
:
19221 case OO
.ui
.Keys
.TAB
:
19222 if ( currentItem
) {
19223 currentItem
.setHighlighted( false );
19225 this.toggle( false );
19226 // Don't prevent tabbing away, prevent defocusing
19227 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
19228 e
.preventDefault();
19229 e
.stopPropagation();
19233 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
19240 * Update menu item visibility after input changes.
19243 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
19245 len
= this.items
.length
,
19246 showAll
= !this.isVisible(),
19247 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() );
19249 for ( i
= 0; i
< len
; i
++ ) {
19250 item
= this.items
[ i
];
19251 if ( item
instanceof OO
.ui
.OptionWidget
) {
19252 item
.toggle( showAll
|| filter( item
) );
19256 // Reevaluate clipping
19263 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
19264 if ( this.$input
) {
19265 this.$input
.on( 'keydown', this.onKeyDownHandler
);
19267 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyDownListener
.call( this );
19274 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
19275 if ( this.$input
) {
19276 this.$input
.off( 'keydown', this.onKeyDownHandler
);
19278 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyDownListener
.call( this );
19285 OO
.ui
.MenuSelectWidget
.prototype.bindKeyPressListener = function () {
19286 if ( this.$input
) {
19287 if ( this.filterFromInput
) {
19288 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
19291 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyPressListener
.call( this );
19298 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyPressListener = function () {
19299 if ( this.$input
) {
19300 if ( this.filterFromInput
) {
19301 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
19302 this.updateItemVisibility();
19305 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyPressListener
.call( this );
19312 * When a user chooses an item, the menu is closed.
19314 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
19315 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
19316 * @param {OO.ui.OptionWidget} item Item to choose
19319 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
19320 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
19321 this.toggle( false );
19328 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
19332 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
19335 if ( !this.newItems
) {
19336 this.newItems
= [];
19339 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
19341 if ( this.isVisible() ) {
19342 // Defer fitting label until item has been attached
19345 this.newItems
.push( item
);
19349 // Reevaluate clipping
19358 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
19360 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
19362 // Reevaluate clipping
19371 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
19373 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
19375 // Reevaluate clipping
19384 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
19385 var i
, len
, change
;
19387 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
19388 change
= visible
!== this.isVisible();
19391 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
19395 this.bindKeyDownListener();
19396 this.bindKeyPressListener();
19398 if ( this.newItems
&& this.newItems
.length
) {
19399 for ( i
= 0, len
= this.newItems
.length
; i
< len
; i
++ ) {
19400 this.newItems
[ i
].fitLabel();
19402 this.newItems
= null;
19404 this.toggleClipping( true );
19407 if ( this.autoHide
) {
19408 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler
);
19411 this.unbindKeyDownListener();
19412 this.unbindKeyPressListener();
19413 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler
);
19414 this.toggleClipping( false );
19422 * FloatingMenuSelectWidget is a menu that will stick under a specified
19423 * container, even when it is inserted elsewhere in the document (for example,
19424 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
19425 * menu from being clipped too aggresively.
19427 * The menu's position is automatically calculated and maintained when the menu
19428 * is toggled or the window is resized.
19430 * See OO.ui.ComboBoxInputWidget for an example of a widget that uses this class.
19433 * @extends OO.ui.MenuSelectWidget
19434 * @mixins OO.ui.mixin.FloatableElement
19437 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
19438 * Deprecated, omit this parameter and specify `$container` instead.
19439 * @param {Object} [config] Configuration options
19440 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
19442 OO
.ui
.FloatingMenuSelectWidget
= function OoUiFloatingMenuSelectWidget( inputWidget
, config
) {
19443 // Allow 'inputWidget' parameter and config for backwards compatibility
19444 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
19445 config
= inputWidget
;
19446 inputWidget
= config
.inputWidget
;
19449 // Configuration initialization
19450 config
= config
|| {};
19452 // Parent constructor
19453 OO
.ui
.FloatingMenuSelectWidget
.parent
.call( this, config
);
19455 // Properties (must be set before mixin constructors)
19456 this.inputWidget
= inputWidget
; // For backwards compatibility
19457 this.$container
= config
.$container
|| this.inputWidget
.$element
;
19459 // Mixins constructors
19460 OO
.ui
.mixin
.FloatableElement
.call( this, $.extend( {}, config
, { $floatableContainer
: this.$container
} ) );
19463 this.$element
.addClass( 'oo-ui-floatingMenuSelectWidget' );
19464 // For backwards compatibility
19465 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
19470 OO
.inheritClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
19471 OO
.mixinClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.mixin
.FloatableElement
);
19473 // For backwards compatibility
19474 OO
.ui
.TextInputMenuSelectWidget
= OO
.ui
.FloatingMenuSelectWidget
;
19481 OO
.ui
.FloatingMenuSelectWidget
.prototype.toggle = function ( visible
) {
19483 visible
= visible
=== undefined ? !this.isVisible() : !!visible
;
19484 change
= visible
!== this.isVisible();
19486 if ( change
&& visible
) {
19487 // Make sure the width is set before the parent method runs.
19488 this.setIdealSize( this.$container
.width() );
19492 // This will call this.clip(), which is nonsensical since we're not positioned yet...
19493 OO
.ui
.FloatingMenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
19496 this.togglePositioning( this.isVisible() );
19503 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
19504 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
19506 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
19509 * @extends OO.ui.SelectWidget
19510 * @mixins OO.ui.mixin.TabIndexedElement
19513 * @param {Object} [config] Configuration options
19515 OO
.ui
.OutlineSelectWidget
= function OoUiOutlineSelectWidget( config
) {
19516 // Parent constructor
19517 OO
.ui
.OutlineSelectWidget
.parent
.call( this, config
);
19519 // Mixin constructors
19520 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
19523 this.$element
.on( {
19524 focus
: this.bindKeyDownListener
.bind( this ),
19525 blur
: this.unbindKeyDownListener
.bind( this )
19529 this.$element
.addClass( 'oo-ui-outlineSelectWidget' );
19534 OO
.inheritClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.SelectWidget
);
19535 OO
.mixinClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
19538 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
19540 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
19543 * @extends OO.ui.SelectWidget
19544 * @mixins OO.ui.mixin.TabIndexedElement
19547 * @param {Object} [config] Configuration options
19549 OO
.ui
.TabSelectWidget
= function OoUiTabSelectWidget( config
) {
19550 // Parent constructor
19551 OO
.ui
.TabSelectWidget
.parent
.call( this, config
);
19553 // Mixin constructors
19554 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
19557 this.$element
.on( {
19558 focus
: this.bindKeyDownListener
.bind( this ),
19559 blur
: this.unbindKeyDownListener
.bind( this )
19563 this.$element
.addClass( 'oo-ui-tabSelectWidget' );
19568 OO
.inheritClass( OO
.ui
.TabSelectWidget
, OO
.ui
.SelectWidget
);
19569 OO
.mixinClass( OO
.ui
.TabSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
19572 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
19573 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
19574 * (to adjust the value in increments) to allow the user to enter a number.
19577 * // Example: A NumberInputWidget.
19578 * var numberInput = new OO.ui.NumberInputWidget( {
19579 * label: 'NumberInputWidget',
19580 * input: { value: 5, min: 1, max: 10 }
19582 * $( 'body' ).append( numberInput.$element );
19585 * @extends OO.ui.Widget
19588 * @param {Object} [config] Configuration options
19589 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
19590 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
19591 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
19592 * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
19593 * @cfg {number} [min=-Infinity] Minimum allowed value
19594 * @cfg {number} [max=Infinity] Maximum allowed value
19595 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
19596 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
19598 OO
.ui
.NumberInputWidget
= function OoUiNumberInputWidget( config
) {
19599 // Configuration initialization
19600 config
= $.extend( {
19608 // Parent constructor
19609 OO
.ui
.NumberInputWidget
.parent
.call( this, config
);
19612 this.input
= new OO
.ui
.TextInputWidget( $.extend(
19614 disabled
: this.isDisabled()
19618 this.minusButton
= new OO
.ui
.ButtonWidget( $.extend(
19620 disabled
: this.isDisabled(),
19623 config
.minusButton
,
19625 classes
: [ 'oo-ui-numberInputWidget-minusButton' ],
19629 this.plusButton
= new OO
.ui
.ButtonWidget( $.extend(
19631 disabled
: this.isDisabled(),
19636 classes
: [ 'oo-ui-numberInputWidget-plusButton' ],
19642 this.input
.connect( this, {
19643 change
: this.emit
.bind( this, 'change' ),
19644 enter
: this.emit
.bind( this, 'enter' )
19646 this.input
.$input
.on( {
19647 keydown
: this.onKeyDown
.bind( this ),
19648 'wheel mousewheel DOMMouseScroll': this.onWheel
.bind( this )
19650 this.plusButton
.connect( this, {
19651 click
: [ 'onButtonClick', +1 ]
19653 this.minusButton
.connect( this, {
19654 click
: [ 'onButtonClick', -1 ]
19658 this.setIsInteger( !!config
.isInteger
);
19659 this.setRange( config
.min
, config
.max
);
19660 this.setStep( config
.step
, config
.pageStep
);
19662 this.$field
= $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
19664 this.minusButton
.$element
,
19665 this.input
.$element
,
19666 this.plusButton
.$element
19668 this.$element
.addClass( 'oo-ui-numberInputWidget' ).append( this.$field
);
19669 this.input
.setValidation( this.validateNumber
.bind( this ) );
19674 OO
.inheritClass( OO
.ui
.NumberInputWidget
, OO
.ui
.Widget
);
19679 * A `change` event is emitted when the value of the input changes.
19685 * An `enter` event is emitted when the user presses 'enter' inside the text box.
19693 * Set whether only integers are allowed
19694 * @param {boolean} flag
19696 OO
.ui
.NumberInputWidget
.prototype.setIsInteger = function ( flag
) {
19697 this.isInteger
= !!flag
;
19698 this.input
.setValidityFlag();
19702 * Get whether only integers are allowed
19703 * @return {boolean} Flag value
19705 OO
.ui
.NumberInputWidget
.prototype.getIsInteger = function () {
19706 return this.isInteger
;
19710 * Set the range of allowed values
19711 * @param {number} min Minimum allowed value
19712 * @param {number} max Maximum allowed value
19714 OO
.ui
.NumberInputWidget
.prototype.setRange = function ( min
, max
) {
19716 throw new Error( 'Minimum (' + min
+ ') must not be greater than maximum (' + max
+ ')' );
19720 this.input
.setValidityFlag();
19724 * Get the current range
19725 * @return {number[]} Minimum and maximum values
19727 OO
.ui
.NumberInputWidget
.prototype.getRange = function () {
19728 return [ this.min
, this.max
];
19732 * Set the stepping deltas
19733 * @param {number} step Normal step
19734 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
19736 OO
.ui
.NumberInputWidget
.prototype.setStep = function ( step
, pageStep
) {
19738 throw new Error( 'Step value must be positive' );
19740 if ( pageStep
=== null ) {
19741 pageStep
= step
* 10;
19742 } else if ( pageStep
<= 0 ) {
19743 throw new Error( 'Page step value must be positive' );
19746 this.pageStep
= pageStep
;
19750 * Get the current stepping values
19751 * @return {number[]} Step and page step
19753 OO
.ui
.NumberInputWidget
.prototype.getStep = function () {
19754 return [ this.step
, this.pageStep
];
19758 * Get the current value of the widget
19761 OO
.ui
.NumberInputWidget
.prototype.getValue = function () {
19762 return this.input
.getValue();
19766 * Get the current value of the widget as a number
19767 * @return {number} May be NaN, or an invalid number
19769 OO
.ui
.NumberInputWidget
.prototype.getNumericValue = function () {
19770 return +this.input
.getValue();
19774 * Set the value of the widget
19775 * @param {string} value Invalid values are allowed
19777 OO
.ui
.NumberInputWidget
.prototype.setValue = function ( value
) {
19778 this.input
.setValue( value
);
19782 * Adjust the value of the widget
19783 * @param {number} delta Adjustment amount
19785 OO
.ui
.NumberInputWidget
.prototype.adjustValue = function ( delta
) {
19786 var n
, v
= this.getNumericValue();
19789 if ( isNaN( delta
) || !isFinite( delta
) ) {
19790 throw new Error( 'Delta must be a finite number' );
19793 if ( isNaN( v
) ) {
19797 n
= Math
.max( Math
.min( n
, this.max
), this.min
);
19798 if ( this.isInteger
) {
19799 n
= Math
.round( n
);
19804 this.setValue( n
);
19811 * @param {string} value Field value
19812 * @return {boolean}
19814 OO
.ui
.NumberInputWidget
.prototype.validateNumber = function ( value
) {
19816 if ( isNaN( n
) || !isFinite( n
) ) {
19820 /*jshint bitwise: false */
19821 if ( this.isInteger
&& ( n
| 0 ) !== n
) {
19824 /*jshint bitwise: true */
19826 if ( n
< this.min
|| n
> this.max
) {
19834 * Handle mouse click events.
19837 * @param {number} dir +1 or -1
19839 OO
.ui
.NumberInputWidget
.prototype.onButtonClick = function ( dir
) {
19840 this.adjustValue( dir
* this.step
);
19844 * Handle mouse wheel events.
19847 * @param {jQuery.Event} event
19849 OO
.ui
.NumberInputWidget
.prototype.onWheel = function ( event
) {
19852 // Standard 'wheel' event
19853 if ( event
.originalEvent
.deltaMode
!== undefined ) {
19854 this.sawWheelEvent
= true;
19856 if ( event
.originalEvent
.deltaY
) {
19857 delta
= -event
.originalEvent
.deltaY
;
19858 } else if ( event
.originalEvent
.deltaX
) {
19859 delta
= event
.originalEvent
.deltaX
;
19862 // Non-standard events
19863 if ( !this.sawWheelEvent
) {
19864 if ( event
.originalEvent
.wheelDeltaX
) {
19865 delta
= -event
.originalEvent
.wheelDeltaX
;
19866 } else if ( event
.originalEvent
.wheelDeltaY
) {
19867 delta
= event
.originalEvent
.wheelDeltaY
;
19868 } else if ( event
.originalEvent
.wheelDelta
) {
19869 delta
= event
.originalEvent
.wheelDelta
;
19870 } else if ( event
.originalEvent
.detail
) {
19871 delta
= -event
.originalEvent
.detail
;
19876 delta
= delta
< 0 ? -1 : 1;
19877 this.adjustValue( delta
* this.step
);
19884 * Handle key down events.
19887 * @param {jQuery.Event} e Key down event
19889 OO
.ui
.NumberInputWidget
.prototype.onKeyDown = function ( e
) {
19890 if ( !this.isDisabled() ) {
19891 switch ( e
.which
) {
19892 case OO
.ui
.Keys
.UP
:
19893 this.adjustValue( this.step
);
19895 case OO
.ui
.Keys
.DOWN
:
19896 this.adjustValue( -this.step
);
19898 case OO
.ui
.Keys
.PAGEUP
:
19899 this.adjustValue( this.pageStep
);
19901 case OO
.ui
.Keys
.PAGEDOWN
:
19902 this.adjustValue( -this.pageStep
);
19911 OO
.ui
.NumberInputWidget
.prototype.setDisabled = function ( disabled
) {
19913 OO
.ui
.NumberInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
19915 if ( this.input
) {
19916 this.input
.setDisabled( this.isDisabled() );
19918 if ( this.minusButton
) {
19919 this.minusButton
.setDisabled( this.isDisabled() );
19921 if ( this.plusButton
) {
19922 this.plusButton
.setDisabled( this.isDisabled() );
19929 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
19930 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
19931 * visually by a slider in the leftmost position.
19934 * // Toggle switches in the 'off' and 'on' position.
19935 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
19936 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
19940 * // Create a FieldsetLayout to layout and label switches
19941 * var fieldset = new OO.ui.FieldsetLayout( {
19942 * label: 'Toggle switches'
19944 * fieldset.addItems( [
19945 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
19946 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
19948 * $( 'body' ).append( fieldset.$element );
19951 * @extends OO.ui.ToggleWidget
19952 * @mixins OO.ui.mixin.TabIndexedElement
19955 * @param {Object} [config] Configuration options
19956 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
19957 * By default, the toggle switch is in the 'off' position.
19959 OO
.ui
.ToggleSwitchWidget
= function OoUiToggleSwitchWidget( config
) {
19960 // Parent constructor
19961 OO
.ui
.ToggleSwitchWidget
.parent
.call( this, config
);
19963 // Mixin constructors
19964 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
19967 this.dragging
= false;
19968 this.dragStart
= null;
19969 this.sliding
= false;
19970 this.$glow
= $( '<span>' );
19971 this.$grip
= $( '<span>' );
19974 this.$element
.on( {
19975 click
: this.onClick
.bind( this ),
19976 keypress
: this.onKeyPress
.bind( this )
19980 this.$glow
.addClass( 'oo-ui-toggleSwitchWidget-glow' );
19981 this.$grip
.addClass( 'oo-ui-toggleSwitchWidget-grip' );
19983 .addClass( 'oo-ui-toggleSwitchWidget' )
19984 .attr( 'role', 'checkbox' )
19985 .append( this.$glow
, this.$grip
);
19990 OO
.inheritClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.ToggleWidget
);
19991 OO
.mixinClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.mixin
.TabIndexedElement
);
19996 * Handle mouse click events.
19999 * @param {jQuery.Event} e Mouse click event
20001 OO
.ui
.ToggleSwitchWidget
.prototype.onClick = function ( e
) {
20002 if ( !this.isDisabled() && e
.which
=== 1 ) {
20003 this.setValue( !this.value
);
20009 * Handle key press events.
20012 * @param {jQuery.Event} e Key press event
20014 OO
.ui
.ToggleSwitchWidget
.prototype.onKeyPress = function ( e
) {
20015 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
20016 this.setValue( !this.value
);