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-09-01T23:25:30Z
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
) {
70 var node
= $element
[ 0 ],
71 nodeName
= node
.nodeName
.toLowerCase(),
72 // Check if the element have tabindex set
73 isInElementGroup
= /^(input|select|textarea|button|object)$/.test( nodeName
),
74 // Check if the element is a link with href or if it has tabindex
76 ( nodeName
=== 'a' && node
.href
) ||
77 !isNaN( $element
.attr( 'tabindex' ) )
79 // Check if the element is visible
81 // This is quicker than calling $element.is( ':visible' )
82 $.expr
.filters
.visible( node
) &&
83 // Check that all parents are visible
84 !$element
.parents().addBack().filter( function () {
85 return $.css( this, 'visibility' ) === 'hidden';
88 isTabOk
= isNaN( $element
.attr( 'tabindex' ) ) || +$element
.attr( 'tabindex' ) >= 0;
91 ( isInElementGroup
? !node
.disabled
: isOtherElement
) &&
97 * Get the user's language and any fallback languages.
99 * These language codes are used to localize user interface elements in the user's language.
101 * In environments that provide a localization system, this function should be overridden to
102 * return the user's language(s). The default implementation returns English (en) only.
104 * @return {string[]} Language codes, in descending order of priority
106 OO
.ui
.getUserLanguages = function () {
111 * Get a value in an object keyed by language code.
113 * @param {Object.<string,Mixed>} obj Object keyed by language code
114 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
115 * @param {string} [fallback] Fallback code, used if no matching language can be found
116 * @return {Mixed} Local value
118 OO
.ui
.getLocalValue = function ( obj
, lang
, fallback
) {
121 // Requested language
125 // Known user language
126 langs
= OO
.ui
.getUserLanguages();
127 for ( i
= 0, len
= langs
.length
; i
< len
; i
++ ) {
134 if ( obj
[ fallback
] ) {
135 return obj
[ fallback
];
137 // First existing language
138 for ( lang
in obj
) {
146 * Check if a node is contained within another node
148 * Similar to jQuery#contains except a list of containers can be supplied
149 * and a boolean argument allows you to include the container in the match list
151 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
152 * @param {HTMLElement} contained Node to find
153 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
154 * @return {boolean} The node is in the list of target nodes
156 OO
.ui
.contains = function ( containers
, contained
, matchContainers
) {
158 if ( !Array
.isArray( containers
) ) {
159 containers
= [ containers
];
161 for ( i
= containers
.length
- 1; i
>= 0; i
-- ) {
162 if ( ( matchContainers
&& contained
=== containers
[ i
] ) || $.contains( containers
[ i
], contained
) ) {
170 * Return a function, that, as long as it continues to be invoked, will not
171 * be triggered. The function will be called after it stops being called for
172 * N milliseconds. If `immediate` is passed, trigger the function on the
173 * leading edge, instead of the trailing.
175 * Ported from: http://underscorejs.org/underscore.js
177 * @param {Function} func
178 * @param {number} wait
179 * @param {boolean} immediate
182 OO
.ui
.debounce = function ( func
, wait
, immediate
) {
187 later = function () {
190 func
.apply( context
, args
);
193 if ( immediate
&& !timeout
) {
194 func
.apply( context
, args
);
196 clearTimeout( timeout
);
197 timeout
= setTimeout( later
, wait
);
202 * Proxy for `node.addEventListener( eventName, handler, true )`, if the browser supports it.
203 * Otherwise falls back to non-capturing event listeners.
205 * @param {HTMLElement} node
206 * @param {string} eventName
207 * @param {Function} handler
209 OO
.ui
.addCaptureEventListener = function ( node
, eventName
, handler
) {
210 if ( node
.addEventListener
) {
211 node
.addEventListener( eventName
, handler
, true );
213 node
.attachEvent( 'on' + eventName
, handler
);
218 * Proxy for `node.removeEventListener( eventName, handler, true )`, if the browser supports it.
219 * Otherwise falls back to non-capturing event listeners.
221 * @param {HTMLElement} node
222 * @param {string} eventName
223 * @param {Function} handler
225 OO
.ui
.removeCaptureEventListener = function ( node
, eventName
, handler
) {
226 if ( node
.addEventListener
) {
227 node
.removeEventListener( eventName
, handler
, true );
229 node
.detachEvent( 'on' + eventName
, handler
);
234 * Reconstitute a JavaScript object corresponding to a widget created by
235 * the PHP implementation.
237 * This is an alias for `OO.ui.Element.static.infuse()`.
239 * @param {string|HTMLElement|jQuery} idOrNode
240 * A DOM id (if a string) or node for the widget to infuse.
241 * @return {OO.ui.Element}
242 * The `OO.ui.Element` corresponding to this (infusable) document node.
244 OO
.ui
.infuse = function ( idOrNode
) {
245 return OO
.ui
.Element
.static.infuse( idOrNode
);
250 * Message store for the default implementation of OO.ui.msg
252 * Environments that provide a localization system should not use this, but should override
253 * OO.ui.msg altogether.
258 // Tool tip for a button that moves items in a list down one place
259 'ooui-outline-control-move-down': 'Move item down',
260 // Tool tip for a button that moves items in a list up one place
261 'ooui-outline-control-move-up': 'Move item up',
262 // Tool tip for a button that removes items from a list
263 'ooui-outline-control-remove': 'Remove item',
264 // Label for the toolbar group that contains a list of all other available tools
265 'ooui-toolbar-more': 'More',
266 // Label for the fake tool that expands the full list of tools in a toolbar group
267 'ooui-toolgroup-expand': 'More',
268 // Label for the fake tool that collapses the full list of tools in a toolbar group
269 'ooui-toolgroup-collapse': 'Fewer',
270 // Default label for the accept button of a confirmation dialog
271 'ooui-dialog-message-accept': 'OK',
272 // Default label for the reject button of a confirmation dialog
273 'ooui-dialog-message-reject': 'Cancel',
274 // Title for process dialog error description
275 'ooui-dialog-process-error': 'Something went wrong',
276 // Label for process dialog dismiss error button, visible when describing errors
277 'ooui-dialog-process-dismiss': 'Dismiss',
278 // Label for process dialog retry action button, visible when describing only recoverable errors
279 'ooui-dialog-process-retry': 'Try again',
280 // Label for process dialog retry action button, visible when describing only warnings
281 'ooui-dialog-process-continue': 'Continue',
282 // Label for the file selection widget's select file button
283 'ooui-selectfile-button-select': 'Select a file',
284 // Label for the file selection widget if file selection is not supported
285 'ooui-selectfile-not-supported': 'File selection is not supported',
286 // Label for the file selection widget when no file is currently selected
287 'ooui-selectfile-placeholder': 'No file is selected',
288 // Label for the file selection widget's drop target
289 'ooui-selectfile-dragdrop-placeholder': 'Drop file here',
290 // Semicolon separator
291 'ooui-semicolon-separator': '; '
295 * Get a localized message.
297 * In environments that provide a localization system, this function should be overridden to
298 * return the message translated in the user's language. The default implementation always returns
301 * After the message key, message parameters may optionally be passed. In the default implementation,
302 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
303 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
304 * they support unnamed, ordered message parameters.
307 * @param {string} key Message key
308 * @param {Mixed...} [params] Message parameters
309 * @return {string} Translated message with parameters substituted
311 OO
.ui
.msg = function ( key
) {
312 var message
= messages
[ key
],
313 params
= Array
.prototype.slice
.call( arguments
, 1 );
314 if ( typeof message
=== 'string' ) {
315 // Perform $1 substitution
316 message
= message
.replace( /\$(\d+)/g, function ( unused
, n
) {
317 var i
= parseInt( n
, 10 );
318 return params
[ i
- 1 ] !== undefined ? params
[ i
- 1 ] : '$' + n
;
321 // Return placeholder if message not found
322 message
= '[' + key
+ ']';
328 * Package a message and arguments for deferred resolution.
330 * Use this when you are statically specifying a message and the message may not yet be present.
332 * @param {string} key Message key
333 * @param {Mixed...} [params] Message parameters
334 * @return {Function} Function that returns the resolved message when executed
336 OO
.ui
.deferMsg = function () {
337 var args
= arguments
;
339 return OO
.ui
.msg
.apply( OO
.ui
, args
);
346 * If the message is a function it will be executed, otherwise it will pass through directly.
348 * @param {Function|string} msg Deferred message, or message text
349 * @return {string} Resolved message
351 OO
.ui
.resolveMsg = function ( msg
) {
352 if ( $.isFunction( msg
) ) {
359 * @param {string} url
362 OO
.ui
.isSafeUrl = function ( url
) {
364 // Keep in sync with php/Tag.php
366 'bitcoin:', 'ftp:', 'ftps:', 'geo:', 'git:', 'gopher:', 'http:', 'https:', 'irc:', 'ircs:',
367 'magnet:', 'mailto:', 'mms:', 'news:', 'nntp:', 'redis:', 'sftp:', 'sip:', 'sips:', 'sms:', 'ssh:',
368 'svn:', 'tel:', 'telnet:', 'urn:', 'worldwind:', 'xmpp:'
371 if ( url
.indexOf( ':' ) === -1 ) {
376 protocol
= url
.split( ':', 1 )[ 0 ] + ':';
377 if ( !protocol
.match( /^([A-za-z0-9\+\.\-])+:/ ) ) {
378 // Not a valid protocol, safe
382 // Safe if in the whitelist
383 return whitelist
.indexOf( protocol
) !== -1;
393 * Namespace for OOjs UI mixins.
395 * Mixins are named according to the type of object they are intended to
396 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
397 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
398 * is intended to be mixed in to an instance of OO.ui.Widget.
406 * PendingElement is a mixin that is used to create elements that notify users that something is happening
407 * and that they should wait before proceeding. The pending state is visually represented with a pending
408 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
409 * field of a {@link OO.ui.TextInputWidget text input widget}.
411 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
412 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
413 * in process dialogs.
416 * function MessageDialog( config ) {
417 * MessageDialog.parent.call( this, config );
419 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
421 * MessageDialog.static.actions = [
422 * { action: 'save', label: 'Done', flags: 'primary' },
423 * { label: 'Cancel', flags: 'safe' }
426 * MessageDialog.prototype.initialize = function () {
427 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
428 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
429 * 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>' );
430 * this.$body.append( this.content.$element );
432 * MessageDialog.prototype.getBodyHeight = function () {
435 * MessageDialog.prototype.getActionProcess = function ( action ) {
437 * if ( action === 'save' ) {
438 * dialog.getActions().get({actions: 'save'})[0].pushPending();
439 * return new OO.ui.Process()
441 * .next( function () {
442 * dialog.getActions().get({actions: 'save'})[0].popPending();
445 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
448 * var windowManager = new OO.ui.WindowManager();
449 * $( 'body' ).append( windowManager.$element );
451 * var dialog = new MessageDialog();
452 * windowManager.addWindows( [ dialog ] );
453 * windowManager.openWindow( dialog );
459 * @param {Object} [config] Configuration options
460 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
462 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
463 // Configuration initialization
464 config
= config
|| {};
468 this.$pending
= null;
471 this.setPendingElement( config
.$pending
|| this.$element
);
476 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
481 * Set the pending element (and clean up any existing one).
483 * @param {jQuery} $pending The element to set to pending.
485 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
486 if ( this.$pending
) {
487 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
490 this.$pending
= $pending
;
491 if ( this.pending
> 0 ) {
492 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
497 * Check if an element is pending.
499 * @return {boolean} Element is pending
501 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
502 return !!this.pending
;
506 * Increase the pending counter. The pending state will remain active until the counter is zero
507 * (i.e., the number of calls to #pushPending and #popPending is the same).
511 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
512 if ( this.pending
=== 0 ) {
513 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
514 this.updateThemeClasses();
522 * Decrease the pending counter. The pending state will remain active until the counter is zero
523 * (i.e., the number of calls to #pushPending and #popPending is the same).
527 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
528 if ( this.pending
=== 1 ) {
529 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
530 this.updateThemeClasses();
532 this.pending
= Math
.max( 0, this.pending
- 1 );
538 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
539 * Actions can be made available for specific contexts (modes) and circumstances
540 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
542 * ActionSets contain two types of actions:
544 * - 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.
545 * - Other: Other actions include all non-special visible actions.
547 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
550 * // Example: An action set used in a process dialog
551 * function MyProcessDialog( config ) {
552 * MyProcessDialog.parent.call( this, config );
554 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
555 * MyProcessDialog.static.title = 'An action set in a process dialog';
556 * // An action set that uses modes ('edit' and 'help' mode, in this example).
557 * MyProcessDialog.static.actions = [
558 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
559 * { action: 'help', modes: 'edit', label: 'Help' },
560 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
561 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
564 * MyProcessDialog.prototype.initialize = function () {
565 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
566 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
567 * 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>' );
568 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
569 * 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>' );
570 * this.stackLayout = new OO.ui.StackLayout( {
571 * items: [ this.panel1, this.panel2 ]
573 * this.$body.append( this.stackLayout.$element );
575 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
576 * return MyProcessDialog.parent.prototype.getSetupProcess.call( this, data )
577 * .next( function () {
578 * this.actions.setMode( 'edit' );
581 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
582 * if ( action === 'help' ) {
583 * this.actions.setMode( 'help' );
584 * this.stackLayout.setItem( this.panel2 );
585 * } else if ( action === 'back' ) {
586 * this.actions.setMode( 'edit' );
587 * this.stackLayout.setItem( this.panel1 );
588 * } else if ( action === 'continue' ) {
590 * return new OO.ui.Process( function () {
594 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
596 * MyProcessDialog.prototype.getBodyHeight = function () {
597 * return this.panel1.$element.outerHeight( true );
599 * var windowManager = new OO.ui.WindowManager();
600 * $( 'body' ).append( windowManager.$element );
601 * var dialog = new MyProcessDialog( {
604 * windowManager.addWindows( [ dialog ] );
605 * windowManager.openWindow( dialog );
607 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
611 * @mixins OO.EventEmitter
614 * @param {Object} [config] Configuration options
616 OO
.ui
.ActionSet
= function OoUiActionSet( config
) {
617 // Configuration initialization
618 config
= config
|| {};
620 // Mixin constructors
621 OO
.EventEmitter
.call( this );
626 actions
: 'getAction',
630 this.categorized
= {};
633 this.organized
= false;
634 this.changing
= false;
635 this.changed
= false;
640 OO
.mixinClass( OO
.ui
.ActionSet
, OO
.EventEmitter
);
642 /* Static Properties */
645 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
646 * header of a {@link OO.ui.ProcessDialog process dialog}.
647 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
649 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
656 OO
.ui
.ActionSet
.static.specialFlags
= [ 'safe', 'primary' ];
663 * A 'click' event is emitted when an action is clicked.
665 * @param {OO.ui.ActionWidget} action Action that was clicked
671 * A 'resize' event is emitted when an action widget is resized.
673 * @param {OO.ui.ActionWidget} action Action that was resized
679 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
681 * @param {OO.ui.ActionWidget[]} added Actions added
687 * A 'remove' event is emitted when actions are {@link #method-remove removed}
688 * or {@link #clear cleared}.
690 * @param {OO.ui.ActionWidget[]} added Actions removed
696 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
697 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
704 * Handle action change events.
709 OO
.ui
.ActionSet
.prototype.onActionChange = function () {
710 this.organized
= false;
711 if ( this.changing
) {
714 this.emit( 'change' );
719 * Check if an action is one of the special actions.
721 * @param {OO.ui.ActionWidget} action Action to check
722 * @return {boolean} Action is special
724 OO
.ui
.ActionSet
.prototype.isSpecial = function ( action
) {
727 for ( flag
in this.special
) {
728 if ( action
=== this.special
[ flag
] ) {
737 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
740 * @param {Object} [filters] Filters to use, omit to get all actions
741 * @param {string|string[]} [filters.actions] Actions that action widgets must have
742 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
743 * @param {string|string[]} [filters.modes] Modes that action widgets must have
744 * @param {boolean} [filters.visible] Action widgets must be visible
745 * @param {boolean} [filters.disabled] Action widgets must be disabled
746 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
748 OO
.ui
.ActionSet
.prototype.get = function ( filters
) {
749 var i
, len
, list
, category
, actions
, index
, match
, matches
;
754 // Collect category candidates
756 for ( category
in this.categorized
) {
757 list
= filters
[ category
];
759 if ( !Array
.isArray( list
) ) {
762 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
763 actions
= this.categorized
[ category
][ list
[ i
] ];
764 if ( Array
.isArray( actions
) ) {
765 matches
.push
.apply( matches
, actions
);
770 // Remove by boolean filters
771 for ( i
= 0, len
= matches
.length
; i
< len
; i
++ ) {
772 match
= matches
[ i
];
774 ( filters
.visible
!== undefined && match
.isVisible() !== filters
.visible
) ||
775 ( filters
.disabled
!== undefined && match
.isDisabled() !== filters
.disabled
)
777 matches
.splice( i
, 1 );
783 for ( i
= 0, len
= matches
.length
; i
< len
; i
++ ) {
784 match
= matches
[ i
];
785 index
= matches
.lastIndexOf( match
);
786 while ( index
!== i
) {
787 matches
.splice( index
, 1 );
789 index
= matches
.lastIndexOf( match
);
794 return this.list
.slice();
798 * Get 'special' actions.
800 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
801 * Special flags can be configured in subclasses by changing the static #specialFlags property.
803 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
805 OO
.ui
.ActionSet
.prototype.getSpecial = function () {
807 return $.extend( {}, this.special
);
811 * Get 'other' actions.
813 * Other actions include all non-special visible action widgets.
815 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
817 OO
.ui
.ActionSet
.prototype.getOthers = function () {
819 return this.others
.slice();
823 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
824 * to be available in the specified mode will be made visible. All other actions will be hidden.
826 * @param {string} mode The mode. Only actions configured to be available in the specified
827 * mode will be made visible.
832 OO
.ui
.ActionSet
.prototype.setMode = function ( mode
) {
835 this.changing
= true;
836 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
837 action
= this.list
[ i
];
838 action
.toggle( action
.hasMode( mode
) );
841 this.organized
= false;
842 this.changing
= false;
843 this.emit( 'change' );
849 * Set the abilities of the specified actions.
851 * Action widgets that are configured with the specified actions will be enabled
852 * or disabled based on the boolean values specified in the `actions`
855 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
856 * values that indicate whether or not the action should be enabled.
859 OO
.ui
.ActionSet
.prototype.setAbilities = function ( actions
) {
860 var i
, len
, action
, item
;
862 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
863 item
= this.list
[ i
];
864 action
= item
.getAction();
865 if ( actions
[ action
] !== undefined ) {
866 item
.setDisabled( !actions
[ action
] );
874 * Executes a function once per action.
876 * When making changes to multiple actions, use this method instead of iterating over the actions
877 * manually to defer emitting a #change event until after all actions have been changed.
879 * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get
880 * @param {Function} callback Callback to run for each action; callback is invoked with three
881 * arguments: the action, the action's index, the list of actions being iterated over
884 OO
.ui
.ActionSet
.prototype.forEach = function ( filter
, callback
) {
885 this.changed
= false;
886 this.changing
= true;
887 this.get( filter
).forEach( callback
);
888 this.changing
= false;
889 if ( this.changed
) {
890 this.emit( 'change' );
897 * Add action widgets to the action set.
899 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
904 OO
.ui
.ActionSet
.prototype.add = function ( actions
) {
907 this.changing
= true;
908 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
909 action
= actions
[ i
];
910 action
.connect( this, {
911 click
: [ 'emit', 'click', action
],
912 resize
: [ 'emit', 'resize', action
],
913 toggle
: [ 'onActionChange' ]
915 this.list
.push( action
);
917 this.organized
= false;
918 this.emit( 'add', actions
);
919 this.changing
= false;
920 this.emit( 'change' );
926 * Remove action widgets from the set.
928 * To remove all actions, you may wish to use the #clear method instead.
930 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
935 OO
.ui
.ActionSet
.prototype.remove = function ( actions
) {
936 var i
, len
, index
, action
;
938 this.changing
= true;
939 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
940 action
= actions
[ i
];
941 index
= this.list
.indexOf( action
);
942 if ( index
!== -1 ) {
943 action
.disconnect( this );
944 this.list
.splice( index
, 1 );
947 this.organized
= false;
948 this.emit( 'remove', actions
);
949 this.changing
= false;
950 this.emit( 'change' );
956 * Remove all action widets from the set.
958 * To remove only specified actions, use the {@link #method-remove remove} method instead.
964 OO
.ui
.ActionSet
.prototype.clear = function () {
966 removed
= this.list
.slice();
968 this.changing
= true;
969 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
970 action
= this.list
[ i
];
971 action
.disconnect( this );
976 this.organized
= false;
977 this.emit( 'remove', removed
);
978 this.changing
= false;
979 this.emit( 'change' );
987 * This is called whenever organized information is requested. It will only reorganize the actions
988 * if something has changed since the last time it ran.
993 OO
.ui
.ActionSet
.prototype.organize = function () {
994 var i
, iLen
, j
, jLen
, flag
, action
, category
, list
, item
, special
,
995 specialFlags
= this.constructor.static.specialFlags
;
997 if ( !this.organized
) {
998 this.categorized
= {};
1001 for ( i
= 0, iLen
= this.list
.length
; i
< iLen
; i
++ ) {
1002 action
= this.list
[ i
];
1003 if ( action
.isVisible() ) {
1004 // Populate categories
1005 for ( category
in this.categories
) {
1006 if ( !this.categorized
[ category
] ) {
1007 this.categorized
[ category
] = {};
1009 list
= action
[ this.categories
[ category
] ]();
1010 if ( !Array
.isArray( list
) ) {
1013 for ( j
= 0, jLen
= list
.length
; j
< jLen
; j
++ ) {
1015 if ( !this.categorized
[ category
][ item
] ) {
1016 this.categorized
[ category
][ item
] = [];
1018 this.categorized
[ category
][ item
].push( action
);
1021 // Populate special/others
1023 for ( j
= 0, jLen
= specialFlags
.length
; j
< jLen
; j
++ ) {
1024 flag
= specialFlags
[ j
];
1025 if ( !this.special
[ flag
] && action
.hasFlag( flag
) ) {
1026 this.special
[ flag
] = action
;
1032 this.others
.push( action
);
1036 this.organized
= true;
1043 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
1044 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
1045 * connected to them and can't be interacted with.
1051 * @param {Object} [config] Configuration options
1052 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
1053 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
1055 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
1056 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
1057 * @cfg {string} [text] Text to insert
1058 * @cfg {Array} [content] An array of content elements to append (after #text).
1059 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
1060 * Instances of OO.ui.Element will have their $element appended.
1061 * @cfg {jQuery} [$content] Content elements to append (after #text)
1062 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
1063 * Data can also be specified with the #setData method.
1065 OO
.ui
.Element
= function OoUiElement( config
) {
1066 // Configuration initialization
1067 config
= config
|| {};
1071 this.visible
= true;
1072 this.data
= config
.data
;
1073 this.$element
= config
.$element
||
1074 $( document
.createElement( this.getTagName() ) );
1075 this.elementGroup
= null;
1076 this.debouncedUpdateThemeClassesHandler
= OO
.ui
.debounce( this.debouncedUpdateThemeClasses
);
1079 if ( Array
.isArray( config
.classes
) ) {
1080 this.$element
.addClass( config
.classes
.join( ' ' ) );
1083 this.$element
.attr( 'id', config
.id
);
1085 if ( config
.text
) {
1086 this.$element
.text( config
.text
);
1088 if ( config
.content
) {
1089 // The `content` property treats plain strings as text; use an
1090 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
1091 // appropriate $element appended.
1092 this.$element
.append( config
.content
.map( function ( v
) {
1093 if ( typeof v
=== 'string' ) {
1094 // Escape string so it is properly represented in HTML.
1095 return document
.createTextNode( v
);
1096 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
1098 return v
.toString();
1099 } else if ( v
instanceof OO
.ui
.Element
) {
1105 if ( config
.$content
) {
1106 // The `$content` property treats plain strings as HTML.
1107 this.$element
.append( config
.$content
);
1113 OO
.initClass( OO
.ui
.Element
);
1115 /* Static Properties */
1118 * The name of the HTML tag used by the element.
1120 * The static value may be ignored if the #getTagName method is overridden.
1124 * @property {string}
1126 OO
.ui
.Element
.static.tagName
= 'div';
1128 /* Static Methods */
1131 * Reconstitute a JavaScript object corresponding to a widget created
1132 * by the PHP implementation.
1134 * @param {string|HTMLElement|jQuery} idOrNode
1135 * A DOM id (if a string) or node for the widget to infuse.
1136 * @return {OO.ui.Element}
1137 * The `OO.ui.Element` corresponding to this (infusable) document node.
1138 * For `Tag` objects emitted on the HTML side (used occasionally for content)
1139 * the value returned is a newly-created Element wrapping around the existing
1142 OO
.ui
.Element
.static.infuse = function ( idOrNode
) {
1143 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, false );
1144 // Verify that the type matches up.
1145 // FIXME: uncomment after T89721 is fixed (see T90929)
1147 if ( !( obj instanceof this['class'] ) ) {
1148 throw new Error( 'Infusion type mismatch!' );
1155 * Implementation helper for `infuse`; skips the type check and has an
1156 * extra property so that only the top-level invocation touches the DOM.
1158 * @param {string|HTMLElement|jQuery} idOrNode
1159 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
1160 * when the top-level widget of this infusion is inserted into DOM,
1161 * replacing the original node; or false for top-level invocation.
1162 * @return {OO.ui.Element}
1164 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, domPromise
) {
1165 // look for a cached result of a previous infusion.
1166 var id
, $elem
, data
, cls
, parts
, parent
, obj
, top
, state
;
1167 if ( typeof idOrNode
=== 'string' ) {
1169 $elem
= $( document
.getElementById( id
) );
1171 $elem
= $( idOrNode
);
1172 id
= $elem
.attr( 'id' );
1174 if ( !$elem
.length
) {
1175 throw new Error( 'Widget not found: ' + id
);
1177 data
= $elem
.data( 'ooui-infused' ) || $elem
[ 0 ].oouiInfused
;
1180 if ( data
=== true ) {
1181 throw new Error( 'Circular dependency! ' + id
);
1185 data
= $elem
.attr( 'data-ooui' );
1187 throw new Error( 'No infusion data found: ' + id
);
1190 data
= $.parseJSON( data
);
1194 if ( !( data
&& data
._
) ) {
1195 throw new Error( 'No valid infusion data found: ' + id
);
1197 if ( data
._
=== 'Tag' ) {
1198 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
1199 return new OO
.ui
.Element( { $element
: $elem
} );
1201 parts
= data
._
.split( '.' );
1202 cls
= OO
.getProp
.apply( OO
, [ window
].concat( parts
) );
1203 if ( cls
=== undefined ) {
1204 // The PHP output might be old and not including the "OO.ui" prefix
1205 // TODO: Remove this back-compat after next major release
1206 cls
= OO
.getProp
.apply( OO
, [ OO
.ui
].concat( parts
) );
1207 if ( cls
=== undefined ) {
1208 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
1212 // Verify that we're creating an OO.ui.Element instance
1213 parent
= cls
.parent
;
1215 while ( parent
!== undefined ) {
1216 if ( parent
=== OO
.ui
.Element
) {
1221 parent
= parent
.parent
;
1224 if ( parent
!== OO
.ui
.Element
) {
1225 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
1228 if ( domPromise
=== false ) {
1230 domPromise
= top
.promise();
1232 $elem
.data( 'ooui-infused', true ); // prevent loops
1233 data
.id
= id
; // implicit
1234 data
= OO
.copy( data
, null, function deserialize( value
) {
1235 if ( OO
.isPlainObject( value
) ) {
1237 return OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, domPromise
);
1240 return new OO
.ui
.HtmlSnippet( value
.html
);
1244 // jscs:disable requireCapitalizedConstructors
1245 obj
= new cls( data
); // rebuild widget
1246 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
1247 state
= obj
.gatherPreInfuseState( $elem
);
1248 // now replace old DOM with this new DOM.
1250 $elem
.replaceWith( obj
.$element
);
1251 // This element is now gone from the DOM, but if anyone is holding a reference to it,
1252 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
1253 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
1254 $elem
[ 0 ].oouiInfused
= obj
;
1257 obj
.$element
.data( 'ooui-infused', obj
);
1258 // set the 'data-ooui' attribute so we can identify infused widgets
1259 obj
.$element
.attr( 'data-ooui', '' );
1260 // restore dynamic state after the new element is inserted into DOM
1261 domPromise
.done( obj
.restorePreInfuseState
.bind( obj
, state
) );
1266 * Get a jQuery function within a specific document.
1269 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1270 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1272 * @return {Function} Bound jQuery function
1274 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
1275 function wrapper( selector
) {
1276 return $( selector
, wrapper
.context
);
1279 wrapper
.context
= this.getDocument( context
);
1282 wrapper
.$iframe
= $iframe
;
1289 * Get the document of an element.
1292 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1293 * @return {HTMLDocument|null} Document object
1295 OO
.ui
.Element
.static.getDocument = function ( obj
) {
1296 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1297 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
1298 // Empty jQuery selections might have a context
1301 obj
.ownerDocument
||
1305 ( obj
.nodeType
=== 9 && obj
) ||
1310 * Get the window of an element or document.
1313 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1314 * @return {Window} Window object
1316 OO
.ui
.Element
.static.getWindow = function ( obj
) {
1317 var doc
= this.getDocument( obj
);
1319 // Standard Document.defaultView is IE9+
1320 return doc
.parentWindow
|| doc
.defaultView
;
1324 * Get the direction of an element or document.
1327 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1328 * @return {string} Text direction, either 'ltr' or 'rtl'
1330 OO
.ui
.Element
.static.getDir = function ( obj
) {
1333 if ( obj
instanceof jQuery
) {
1336 isDoc
= obj
.nodeType
=== 9;
1337 isWin
= obj
.document
!== undefined;
1338 if ( isDoc
|| isWin
) {
1344 return $( obj
).css( 'direction' );
1348 * Get the offset between two frames.
1350 * TODO: Make this function not use recursion.
1353 * @param {Window} from Window of the child frame
1354 * @param {Window} [to=window] Window of the parent frame
1355 * @param {Object} [offset] Offset to start with, used internally
1356 * @return {Object} Offset object, containing left and top properties
1358 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
1359 var i
, len
, frames
, frame
, rect
;
1365 offset
= { top
: 0, left
: 0 };
1367 if ( from.parent
=== from ) {
1371 // Get iframe element
1372 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
1373 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
1374 if ( frames
[ i
].contentWindow
=== from ) {
1375 frame
= frames
[ i
];
1380 // Recursively accumulate offset values
1382 rect
= frame
.getBoundingClientRect();
1383 offset
.left
+= rect
.left
;
1384 offset
.top
+= rect
.top
;
1385 if ( from !== to
) {
1386 this.getFrameOffset( from.parent
, offset
);
1393 * Get the offset between two elements.
1395 * The two elements may be in a different frame, but in that case the frame $element is in must
1396 * be contained in the frame $anchor is in.
1399 * @param {jQuery} $element Element whose position to get
1400 * @param {jQuery} $anchor Element to get $element's position relative to
1401 * @return {Object} Translated position coordinates, containing top and left properties
1403 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
1404 var iframe
, iframePos
,
1405 pos
= $element
.offset(),
1406 anchorPos
= $anchor
.offset(),
1407 elementDocument
= this.getDocument( $element
),
1408 anchorDocument
= this.getDocument( $anchor
);
1410 // If $element isn't in the same document as $anchor, traverse up
1411 while ( elementDocument
!== anchorDocument
) {
1412 iframe
= elementDocument
.defaultView
.frameElement
;
1414 throw new Error( '$element frame is not contained in $anchor frame' );
1416 iframePos
= $( iframe
).offset();
1417 pos
.left
+= iframePos
.left
;
1418 pos
.top
+= iframePos
.top
;
1419 elementDocument
= iframe
.ownerDocument
;
1421 pos
.left
-= anchorPos
.left
;
1422 pos
.top
-= anchorPos
.top
;
1427 * Get element border sizes.
1430 * @param {HTMLElement} el Element to measure
1431 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1433 OO
.ui
.Element
.static.getBorders = function ( el
) {
1434 var doc
= el
.ownerDocument
,
1436 // Standard Document.defaultView is IE9+
1437 win
= doc
.parentWindow
|| doc
.defaultView
,
1438 style
= win
&& win
.getComputedStyle
?
1439 win
.getComputedStyle( el
, null ) :
1441 // Standard getComputedStyle() is IE9+
1444 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
1445 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
1446 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
1447 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
1458 * Get dimensions of an element or window.
1461 * @param {HTMLElement|Window} el Element to measure
1462 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1464 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1466 doc
= el
.ownerDocument
|| el
.document
,
1468 // Standard Document.defaultView is IE9+
1469 win
= doc
.parentWindow
|| doc
.defaultView
;
1471 if ( win
=== el
|| el
=== doc
.documentElement
) {
1474 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1476 top
: $win
.scrollTop(),
1477 left
: $win
.scrollLeft()
1479 scrollbar
: { right
: 0, bottom
: 0 },
1483 bottom
: $win
.innerHeight(),
1484 right
: $win
.innerWidth()
1490 borders
: this.getBorders( el
),
1492 top
: $el
.scrollTop(),
1493 left
: $el
.scrollLeft()
1496 right
: $el
.innerWidth() - el
.clientWidth
,
1497 bottom
: $el
.innerHeight() - el
.clientHeight
1499 rect
: el
.getBoundingClientRect()
1505 * Get scrollable object parent
1507 * documentElement can't be used to get or set the scrollTop
1508 * property on Blink. Changing and testing its value lets us
1509 * use 'body' or 'documentElement' based on what is working.
1511 * https://code.google.com/p/chromium/issues/detail?id=303131
1514 * @param {HTMLElement} el Element to find scrollable parent for
1515 * @return {HTMLElement} Scrollable parent
1517 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1518 var scrollTop
, body
;
1520 if ( OO
.ui
.scrollableElement
=== undefined ) {
1521 body
= el
.ownerDocument
.body
;
1522 scrollTop
= body
.scrollTop
;
1525 if ( body
.scrollTop
=== 1 ) {
1526 body
.scrollTop
= scrollTop
;
1527 OO
.ui
.scrollableElement
= 'body';
1529 OO
.ui
.scrollableElement
= 'documentElement';
1533 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1537 * Get closest scrollable container.
1539 * Traverses up until either a scrollable element or the root is reached, in which case the window
1543 * @param {HTMLElement} el Element to find scrollable container for
1544 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1545 * @return {HTMLElement} Closest scrollable container
1547 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1549 // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
1550 props
= [ 'overflow-x', 'overflow-y' ],
1551 $parent
= $( el
).parent();
1553 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1554 props
= [ 'overflow-' + dimension
];
1557 while ( $parent
.length
) {
1558 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1559 return $parent
[ 0 ];
1563 val
= $parent
.css( props
[ i
] );
1564 if ( val
=== 'auto' || val
=== 'scroll' ) {
1565 return $parent
[ 0 ];
1568 $parent
= $parent
.parent();
1570 return this.getDocument( el
).body
;
1574 * Scroll element into view.
1577 * @param {HTMLElement} el Element to scroll into view
1578 * @param {Object} [config] Configuration options
1579 * @param {string} [config.duration] jQuery animation duration value
1580 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1581 * to scroll in both directions
1582 * @param {Function} [config.complete] Function to call when scrolling completes
1584 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1585 var rel
, anim
, callback
, sc
, $sc
, eld
, scd
, $win
;
1587 // Configuration initialization
1588 config
= config
|| {};
1591 callback
= typeof config
.complete
=== 'function' && config
.complete
;
1592 sc
= this.getClosestScrollableContainer( el
, config
.direction
);
1594 eld
= this.getDimensions( el
);
1595 scd
= this.getDimensions( sc
);
1596 $win
= $( this.getWindow( el
) );
1598 // Compute the distances between the edges of el and the edges of the scroll viewport
1599 if ( $sc
.is( 'html, body' ) ) {
1600 // If the scrollable container is the root, this is easy
1603 bottom
: $win
.innerHeight() - eld
.rect
.bottom
,
1604 left
: eld
.rect
.left
,
1605 right
: $win
.innerWidth() - eld
.rect
.right
1608 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1610 top
: eld
.rect
.top
- ( scd
.rect
.top
+ scd
.borders
.top
),
1611 bottom
: scd
.rect
.bottom
- scd
.borders
.bottom
- scd
.scrollbar
.bottom
- eld
.rect
.bottom
,
1612 left
: eld
.rect
.left
- ( scd
.rect
.left
+ scd
.borders
.left
),
1613 right
: scd
.rect
.right
- scd
.borders
.right
- scd
.scrollbar
.right
- eld
.rect
.right
1617 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1618 if ( rel
.top
< 0 ) {
1619 anim
.scrollTop
= scd
.scroll
.top
+ rel
.top
;
1620 } else if ( rel
.top
> 0 && rel
.bottom
< 0 ) {
1621 anim
.scrollTop
= scd
.scroll
.top
+ Math
.min( rel
.top
, -rel
.bottom
);
1624 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1625 if ( rel
.left
< 0 ) {
1626 anim
.scrollLeft
= scd
.scroll
.left
+ rel
.left
;
1627 } else if ( rel
.left
> 0 && rel
.right
< 0 ) {
1628 anim
.scrollLeft
= scd
.scroll
.left
+ Math
.min( rel
.left
, -rel
.right
);
1631 if ( !$.isEmptyObject( anim
) ) {
1632 $sc
.stop( true ).animate( anim
, config
.duration
|| 'fast' );
1634 $sc
.queue( function ( next
) {
1647 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1648 * and reserve space for them, because it probably doesn't.
1650 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1651 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1652 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1653 * and then reattach (or show) them back.
1656 * @param {HTMLElement} el Element to reconsider the scrollbars on
1658 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1659 var i
, len
, scrollLeft
, scrollTop
, nodes
= [];
1660 // Save scroll position
1661 scrollLeft
= el
.scrollLeft
;
1662 scrollTop
= el
.scrollTop
;
1663 // Detach all children
1664 while ( el
.firstChild
) {
1665 nodes
.push( el
.firstChild
);
1666 el
.removeChild( el
.firstChild
);
1669 void el
.offsetHeight
;
1670 // Reattach all children
1671 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1672 el
.appendChild( nodes
[ i
] );
1674 // Restore scroll position (no-op if scrollbars disappeared)
1675 el
.scrollLeft
= scrollLeft
;
1676 el
.scrollTop
= scrollTop
;
1682 * Toggle visibility of an element.
1684 * @param {boolean} [show] Make element visible, omit to toggle visibility
1688 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1689 show
= show
=== undefined ? !this.visible
: !!show
;
1691 if ( show
!== this.isVisible() ) {
1692 this.visible
= show
;
1693 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1694 this.emit( 'toggle', show
);
1701 * Check if element is visible.
1703 * @return {boolean} element is visible
1705 OO
.ui
.Element
.prototype.isVisible = function () {
1706 return this.visible
;
1712 * @return {Mixed} Element data
1714 OO
.ui
.Element
.prototype.getData = function () {
1721 * @param {Mixed} Element data
1724 OO
.ui
.Element
.prototype.setData = function ( data
) {
1730 * Check if element supports one or more methods.
1732 * @param {string|string[]} methods Method or list of methods to check
1733 * @return {boolean} All methods are supported
1735 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1739 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1740 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1741 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1746 return methods
.length
=== support
;
1750 * Update the theme-provided classes.
1752 * @localdoc This is called in element mixins and widget classes any time state changes.
1753 * Updating is debounced, minimizing overhead of changing multiple attributes and
1754 * guaranteeing that theme updates do not occur within an element's constructor
1756 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1757 this.debouncedUpdateThemeClassesHandler();
1762 * @localdoc This method is called directly from the QUnit tests instead of #updateThemeClasses, to
1763 * make them synchronous.
1765 OO
.ui
.Element
.prototype.debouncedUpdateThemeClasses = function () {
1766 OO
.ui
.theme
.updateElementClasses( this );
1770 * Get the HTML tag name.
1772 * Override this method to base the result on instance information.
1774 * @return {string} HTML tag name
1776 OO
.ui
.Element
.prototype.getTagName = function () {
1777 return this.constructor.static.tagName
;
1781 * Check if the element is attached to the DOM
1782 * @return {boolean} The element is attached to the DOM
1784 OO
.ui
.Element
.prototype.isElementAttached = function () {
1785 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1789 * Get the DOM document.
1791 * @return {HTMLDocument} Document object
1793 OO
.ui
.Element
.prototype.getElementDocument = function () {
1794 // Don't cache this in other ways either because subclasses could can change this.$element
1795 return OO
.ui
.Element
.static.getDocument( this.$element
);
1799 * Get the DOM window.
1801 * @return {Window} Window object
1803 OO
.ui
.Element
.prototype.getElementWindow = function () {
1804 return OO
.ui
.Element
.static.getWindow( this.$element
);
1808 * Get closest scrollable container.
1810 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1811 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1815 * Get group element is in.
1817 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1819 OO
.ui
.Element
.prototype.getElementGroup = function () {
1820 return this.elementGroup
;
1824 * Set group element is in.
1826 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1829 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1830 this.elementGroup
= group
;
1835 * Scroll element into view.
1837 * @param {Object} [config] Configuration options
1839 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1840 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1844 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of a HTML DOM node
1845 * (and its children) that represent an Element of the same type and configuration as the current
1846 * one, generated by the PHP implementation.
1848 * This method is called just before `node` is detached from the DOM. The return value of this
1849 * function will be passed to #restorePreInfuseState after this widget's #$element is inserted into
1850 * DOM to replace `node`.
1853 * @param {HTMLElement} node
1856 OO
.ui
.Element
.prototype.gatherPreInfuseState = function () {
1861 * Restore the pre-infusion dynamic state for this widget.
1863 * This method is called after #$element has been inserted into DOM. The parameter is the return
1864 * value of #gatherPreInfuseState.
1867 * @param {Object} state
1869 OO
.ui
.Element
.prototype.restorePreInfuseState = function () {
1873 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1874 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1875 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1876 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1877 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1881 * @extends OO.ui.Element
1882 * @mixins OO.EventEmitter
1885 * @param {Object} [config] Configuration options
1887 OO
.ui
.Layout
= function OoUiLayout( config
) {
1888 // Configuration initialization
1889 config
= config
|| {};
1891 // Parent constructor
1892 OO
.ui
.Layout
.parent
.call( this, config
);
1894 // Mixin constructors
1895 OO
.EventEmitter
.call( this );
1898 this.$element
.addClass( 'oo-ui-layout' );
1903 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1904 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1907 * Widgets are compositions of one or more OOjs UI elements that users can both view
1908 * and interact with. All widgets can be configured and modified via a standard API,
1909 * and their state can change dynamically according to a model.
1913 * @extends OO.ui.Element
1914 * @mixins OO.EventEmitter
1917 * @param {Object} [config] Configuration options
1918 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1919 * appearance reflects this state.
1921 OO
.ui
.Widget
= function OoUiWidget( config
) {
1922 // Initialize config
1923 config
= $.extend( { disabled
: false }, config
);
1925 // Parent constructor
1926 OO
.ui
.Widget
.parent
.call( this, config
);
1928 // Mixin constructors
1929 OO
.EventEmitter
.call( this );
1932 this.disabled
= null;
1933 this.wasDisabled
= null;
1936 this.$element
.addClass( 'oo-ui-widget' );
1937 this.setDisabled( !!config
.disabled
);
1942 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1943 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1945 /* Static Properties */
1948 * Whether this widget will behave reasonably when wrapped in a HTML `<label>`. If this is true,
1949 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
1954 * @property {boolean}
1956 OO
.ui
.Widget
.static.supportsSimpleLabel
= false;
1963 * A 'disable' event is emitted when a widget is disabled.
1965 * @param {boolean} disabled Widget is disabled
1971 * A 'toggle' event is emitted when the visibility of the widget changes.
1973 * @param {boolean} visible Widget is visible
1979 * Check if the widget is disabled.
1981 * @return {boolean} Widget is disabled
1983 OO
.ui
.Widget
.prototype.isDisabled = function () {
1984 return this.disabled
;
1988 * Set the 'disabled' state of the widget.
1990 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1992 * @param {boolean} disabled Disable widget
1995 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
1998 this.disabled
= !!disabled
;
1999 isDisabled
= this.isDisabled();
2000 if ( isDisabled
!== this.wasDisabled
) {
2001 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
2002 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
2003 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
2004 this.emit( 'disable', isDisabled
);
2005 this.updateThemeClasses();
2007 this.wasDisabled
= isDisabled
;
2013 * Update the disabled state, in case of changes in parent widget.
2017 OO
.ui
.Widget
.prototype.updateDisabled = function () {
2018 this.setDisabled( this.disabled
);
2023 * A window is a container for elements that are in a child frame. They are used with
2024 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
2025 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
2026 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
2027 * the window manager will choose a sensible fallback.
2029 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
2030 * different processes are executed:
2032 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
2033 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
2036 * - {@link #getSetupProcess} method is called and its result executed
2037 * - {@link #getReadyProcess} method is called and its result executed
2039 * **opened**: The window is now open
2041 * **closing**: The closing stage begins when the window manager's
2042 * {@link OO.ui.WindowManager#closeWindow closeWindow}
2043 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
2045 * - {@link #getHoldProcess} method is called and its result executed
2046 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
2048 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
2049 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
2050 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
2051 * processing can complete. Always assume window processes are executed asynchronously.
2053 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2055 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
2059 * @extends OO.ui.Element
2060 * @mixins OO.EventEmitter
2063 * @param {Object} [config] Configuration options
2064 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
2065 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
2067 OO
.ui
.Window
= function OoUiWindow( config
) {
2068 // Configuration initialization
2069 config
= config
|| {};
2071 // Parent constructor
2072 OO
.ui
.Window
.parent
.call( this, config
);
2074 // Mixin constructors
2075 OO
.EventEmitter
.call( this );
2078 this.manager
= null;
2079 this.size
= config
.size
|| this.constructor.static.size
;
2080 this.$frame
= $( '<div>' );
2081 this.$overlay
= $( '<div>' );
2082 this.$content
= $( '<div>' );
2085 this.$overlay
.addClass( 'oo-ui-window-overlay' );
2087 .addClass( 'oo-ui-window-content' )
2088 .attr( 'tabindex', 0 );
2090 .addClass( 'oo-ui-window-frame' )
2091 .append( this.$content
);
2094 .addClass( 'oo-ui-window' )
2095 .append( this.$frame
, this.$overlay
);
2097 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
2098 // that reference properties not initialized at that time of parent class construction
2099 // TODO: Find a better way to handle post-constructor setup
2100 this.visible
= false;
2101 this.$element
.addClass( 'oo-ui-element-hidden' );
2106 OO
.inheritClass( OO
.ui
.Window
, OO
.ui
.Element
);
2107 OO
.mixinClass( OO
.ui
.Window
, OO
.EventEmitter
);
2109 /* Static Properties */
2112 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
2114 * The static size is used if no #size is configured during construction.
2118 * @property {string}
2120 OO
.ui
.Window
.static.size
= 'medium';
2125 * Handle mouse down events.
2128 * @param {jQuery.Event} e Mouse down event
2130 OO
.ui
.Window
.prototype.onMouseDown = function ( e
) {
2131 // Prevent clicking on the click-block from stealing focus
2132 if ( e
.target
=== this.$element
[ 0 ] ) {
2138 * Check if the window has been initialized.
2140 * Initialization occurs when a window is added to a manager.
2142 * @return {boolean} Window has been initialized
2144 OO
.ui
.Window
.prototype.isInitialized = function () {
2145 return !!this.manager
;
2149 * Check if the window is visible.
2151 * @return {boolean} Window is visible
2153 OO
.ui
.Window
.prototype.isVisible = function () {
2154 return this.visible
;
2158 * Check if the window is opening.
2160 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
2163 * @return {boolean} Window is opening
2165 OO
.ui
.Window
.prototype.isOpening = function () {
2166 return this.manager
.isOpening( this );
2170 * Check if the window is closing.
2172 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
2174 * @return {boolean} Window is closing
2176 OO
.ui
.Window
.prototype.isClosing = function () {
2177 return this.manager
.isClosing( this );
2181 * Check if the window is opened.
2183 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
2185 * @return {boolean} Window is opened
2187 OO
.ui
.Window
.prototype.isOpened = function () {
2188 return this.manager
.isOpened( this );
2192 * Get the window manager.
2194 * All windows must be attached to a window manager, which is used to open
2195 * and close the window and control its presentation.
2197 * @return {OO.ui.WindowManager} Manager of window
2199 OO
.ui
.Window
.prototype.getManager = function () {
2200 return this.manager
;
2204 * Get the symbolic name of the window size (e.g., `small` or `medium`).
2206 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
2208 OO
.ui
.Window
.prototype.getSize = function () {
2209 var viewport
= OO
.ui
.Element
.static.getDimensions( this.getElementWindow() ),
2210 sizes
= this.manager
.constructor.static.sizes
,
2213 if ( !sizes
[ size
] ) {
2214 size
= this.manager
.constructor.static.defaultSize
;
2216 if ( size
!== 'full' && viewport
.rect
.right
- viewport
.rect
.left
< sizes
[ size
].width
) {
2224 * Get the size properties associated with the current window size
2226 * @return {Object} Size properties
2228 OO
.ui
.Window
.prototype.getSizeProperties = function () {
2229 return this.manager
.constructor.static.sizes
[ this.getSize() ];
2233 * Disable transitions on window's frame for the duration of the callback function, then enable them
2237 * @param {Function} callback Function to call while transitions are disabled
2239 OO
.ui
.Window
.prototype.withoutSizeTransitions = function ( callback
) {
2240 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2241 // Disable transitions first, otherwise we'll get values from when the window was animating.
2243 styleObj
= this.$frame
[ 0 ].style
;
2244 oldTransition
= styleObj
.transition
|| styleObj
.OTransition
|| styleObj
.MsTransition
||
2245 styleObj
.MozTransition
|| styleObj
.WebkitTransition
;
2246 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
2247 styleObj
.MozTransition
= styleObj
.WebkitTransition
= 'none';
2249 // Force reflow to make sure the style changes done inside callback really are not transitioned
2250 this.$frame
.height();
2251 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
2252 styleObj
.MozTransition
= styleObj
.WebkitTransition
= oldTransition
;
2256 * Get the height of the full window contents (i.e., the window head, body and foot together).
2258 * What consistitutes the head, body, and foot varies depending on the window type.
2259 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
2260 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
2261 * and special actions in the head, and dialog content in the body.
2263 * To get just the height of the dialog body, use the #getBodyHeight method.
2265 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
2267 OO
.ui
.Window
.prototype.getContentHeight = function () {
2270 bodyStyleObj
= this.$body
[ 0 ].style
,
2271 frameStyleObj
= this.$frame
[ 0 ].style
;
2273 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2274 // Disable transitions first, otherwise we'll get values from when the window was animating.
2275 this.withoutSizeTransitions( function () {
2276 var oldHeight
= frameStyleObj
.height
,
2277 oldPosition
= bodyStyleObj
.position
;
2278 frameStyleObj
.height
= '1px';
2279 // Force body to resize to new width
2280 bodyStyleObj
.position
= 'relative';
2281 bodyHeight
= win
.getBodyHeight();
2282 frameStyleObj
.height
= oldHeight
;
2283 bodyStyleObj
.position
= oldPosition
;
2287 // Add buffer for border
2288 ( this.$frame
.outerHeight() - this.$frame
.innerHeight() ) +
2289 // Use combined heights of children
2290 ( this.$head
.outerHeight( true ) + bodyHeight
+ this.$foot
.outerHeight( true ) )
2295 * Get the height of the window body.
2297 * To get the height of the full window contents (the window body, head, and foot together),
2298 * use #getContentHeight.
2300 * When this function is called, the window will temporarily have been resized
2301 * to height=1px, so .scrollHeight measurements can be taken accurately.
2303 * @return {number} Height of the window body in pixels
2305 OO
.ui
.Window
.prototype.getBodyHeight = function () {
2306 return this.$body
[ 0 ].scrollHeight
;
2310 * Get the directionality of the frame (right-to-left or left-to-right).
2312 * @return {string} Directionality: `'ltr'` or `'rtl'`
2314 OO
.ui
.Window
.prototype.getDir = function () {
2315 return OO
.ui
.Element
.static.getDir( this.$content
) || 'ltr';
2319 * Get the 'setup' process.
2321 * The setup process is used to set up a window for use in a particular context,
2322 * based on the `data` argument. This method is called during the opening phase of the window’s
2325 * Override this method to add additional steps to the ‘setup’ process the parent method provides
2326 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2329 * To add window content that persists between openings, you may wish to use the #initialize method
2333 * @param {Object} [data] Window opening data
2334 * @return {OO.ui.Process} Setup process
2336 OO
.ui
.Window
.prototype.getSetupProcess = function () {
2337 return new OO
.ui
.Process();
2341 * Get the ‘ready’ process.
2343 * The ready process is used to ready a window for use in a particular
2344 * context, based on the `data` argument. This method is called during the opening phase of
2345 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2347 * Override this method to add additional steps to the ‘ready’ process the parent method
2348 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2349 * methods of OO.ui.Process.
2352 * @param {Object} [data] Window opening data
2353 * @return {OO.ui.Process} Ready process
2355 OO
.ui
.Window
.prototype.getReadyProcess = function () {
2356 return new OO
.ui
.Process();
2360 * Get the 'hold' process.
2362 * The hold proccess is used to keep a window from being used in a particular context,
2363 * based on the `data` argument. This method is called during the closing phase of the window’s
2366 * Override this method to add additional steps to the 'hold' process the parent method provides
2367 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2371 * @param {Object} [data] Window closing data
2372 * @return {OO.ui.Process} Hold process
2374 OO
.ui
.Window
.prototype.getHoldProcess = function () {
2375 return new OO
.ui
.Process();
2379 * Get the ‘teardown’ process.
2381 * The teardown process is used to teardown a window after use. During teardown,
2382 * user interactions within the window are conveyed and the window is closed, based on the `data`
2383 * argument. This method is called during the closing phase of the window’s lifecycle.
2385 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2386 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2390 * @param {Object} [data] Window closing data
2391 * @return {OO.ui.Process} Teardown process
2393 OO
.ui
.Window
.prototype.getTeardownProcess = function () {
2394 return new OO
.ui
.Process();
2398 * Set the window manager.
2400 * This will cause the window to initialize. Calling it more than once will cause an error.
2402 * @param {OO.ui.WindowManager} manager Manager for this window
2403 * @throws {Error} An error is thrown if the method is called more than once
2406 OO
.ui
.Window
.prototype.setManager = function ( manager
) {
2407 if ( this.manager
) {
2408 throw new Error( 'Cannot set window manager, window already has a manager' );
2411 this.manager
= manager
;
2418 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2420 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2424 OO
.ui
.Window
.prototype.setSize = function ( size
) {
2431 * Update the window size.
2433 * @throws {Error} An error is thrown if the window is not attached to a window manager
2436 OO
.ui
.Window
.prototype.updateSize = function () {
2437 if ( !this.manager
) {
2438 throw new Error( 'Cannot update window size, must be attached to a manager' );
2441 this.manager
.updateWindowSize( this );
2447 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2448 * when the window is opening. In general, setDimensions should not be called directly.
2450 * To set the size of the window, use the #setSize method.
2452 * @param {Object} dim CSS dimension properties
2453 * @param {string|number} [dim.width] Width
2454 * @param {string|number} [dim.minWidth] Minimum width
2455 * @param {string|number} [dim.maxWidth] Maximum width
2456 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2457 * @param {string|number} [dim.minWidth] Minimum height
2458 * @param {string|number} [dim.maxWidth] Maximum height
2461 OO
.ui
.Window
.prototype.setDimensions = function ( dim
) {
2464 styleObj
= this.$frame
[ 0 ].style
;
2466 // Calculate the height we need to set using the correct width
2467 if ( dim
.height
=== undefined ) {
2468 this.withoutSizeTransitions( function () {
2469 var oldWidth
= styleObj
.width
;
2470 win
.$frame
.css( 'width', dim
.width
|| '' );
2471 height
= win
.getContentHeight();
2472 styleObj
.width
= oldWidth
;
2475 height
= dim
.height
;
2479 width
: dim
.width
|| '',
2480 minWidth
: dim
.minWidth
|| '',
2481 maxWidth
: dim
.maxWidth
|| '',
2482 height
: height
|| '',
2483 minHeight
: dim
.minHeight
|| '',
2484 maxHeight
: dim
.maxHeight
|| ''
2491 * Initialize window contents.
2493 * Before the window is opened for the first time, #initialize is called so that content that
2494 * persists between openings can be added to the window.
2496 * To set up a window with new content each time the window opens, use #getSetupProcess.
2498 * @throws {Error} An error is thrown if the window is not attached to a window manager
2501 OO
.ui
.Window
.prototype.initialize = function () {
2502 if ( !this.manager
) {
2503 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2507 this.$head
= $( '<div>' );
2508 this.$body
= $( '<div>' );
2509 this.$foot
= $( '<div>' );
2510 this.$document
= $( this.getElementDocument() );
2513 this.$element
.on( 'mousedown', this.onMouseDown
.bind( this ) );
2516 this.$head
.addClass( 'oo-ui-window-head' );
2517 this.$body
.addClass( 'oo-ui-window-body' );
2518 this.$foot
.addClass( 'oo-ui-window-foot' );
2519 this.$content
.append( this.$head
, this.$body
, this.$foot
);
2527 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2528 * method, which returns a promise resolved when the window is done opening.
2530 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2532 * @param {Object} [data] Window opening data
2533 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2534 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2535 * value is a new promise, which is resolved when the window begins closing.
2536 * @throws {Error} An error is thrown if the window is not attached to a window manager
2538 OO
.ui
.Window
.prototype.open = function ( data
) {
2539 if ( !this.manager
) {
2540 throw new Error( 'Cannot open window, must be attached to a manager' );
2543 return this.manager
.openWindow( this, data
);
2549 * This method is a wrapper around a call to the window
2550 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2551 * which returns a closing promise resolved when the window is done closing.
2553 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2554 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2555 * the window closes.
2557 * @param {Object} [data] Window closing data
2558 * @return {jQuery.Promise} Promise resolved when window is closed
2559 * @throws {Error} An error is thrown if the window is not attached to a window manager
2561 OO
.ui
.Window
.prototype.close = function ( data
) {
2562 if ( !this.manager
) {
2563 throw new Error( 'Cannot close window, must be attached to a manager' );
2566 return this.manager
.closeWindow( this, data
);
2572 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2575 * @param {Object} [data] Window opening data
2576 * @return {jQuery.Promise} Promise resolved when window is setup
2578 OO
.ui
.Window
.prototype.setup = function ( data
) {
2580 deferred
= $.Deferred();
2582 this.toggle( true );
2584 this.getSetupProcess( data
).execute().done( function () {
2585 // Force redraw by asking the browser to measure the elements' widths
2586 win
.$element
.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2587 win
.$content
.addClass( 'oo-ui-window-content-setup' ).width();
2591 return deferred
.promise();
2597 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2600 * @param {Object} [data] Window opening data
2601 * @return {jQuery.Promise} Promise resolved when window is ready
2603 OO
.ui
.Window
.prototype.ready = function ( data
) {
2605 deferred
= $.Deferred();
2607 this.$content
.focus();
2608 this.getReadyProcess( data
).execute().done( function () {
2609 // Force redraw by asking the browser to measure the elements' widths
2610 win
.$element
.addClass( 'oo-ui-window-ready' ).width();
2611 win
.$content
.addClass( 'oo-ui-window-content-ready' ).width();
2615 return deferred
.promise();
2621 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2624 * @param {Object} [data] Window closing data
2625 * @return {jQuery.Promise} Promise resolved when window is held
2627 OO
.ui
.Window
.prototype.hold = function ( data
) {
2629 deferred
= $.Deferred();
2631 this.getHoldProcess( data
).execute().done( function () {
2632 // Get the focused element within the window's content
2633 var $focus
= win
.$content
.find( OO
.ui
.Element
.static.getDocument( win
.$content
).activeElement
);
2635 // Blur the focused element
2636 if ( $focus
.length
) {
2640 // Force redraw by asking the browser to measure the elements' widths
2641 win
.$element
.removeClass( 'oo-ui-window-ready' ).width();
2642 win
.$content
.removeClass( 'oo-ui-window-content-ready' ).width();
2646 return deferred
.promise();
2652 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2655 * @param {Object} [data] Window closing data
2656 * @return {jQuery.Promise} Promise resolved when window is torn down
2658 OO
.ui
.Window
.prototype.teardown = function ( data
) {
2661 return this.getTeardownProcess( data
).execute()
2662 .done( function () {
2663 // Force redraw by asking the browser to measure the elements' widths
2664 win
.$element
.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2665 win
.$content
.removeClass( 'oo-ui-window-content-setup' ).width();
2666 win
.toggle( false );
2671 * The Dialog class serves as the base class for the other types of dialogs.
2672 * Unless extended to include controls, the rendered dialog box is a simple window
2673 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2674 * which opens, closes, and controls the presentation of the window. See the
2675 * [OOjs UI documentation on MediaWiki] [1] for more information.
2678 * // A simple dialog window.
2679 * function MyDialog( config ) {
2680 * MyDialog.parent.call( this, config );
2682 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2683 * MyDialog.prototype.initialize = function () {
2684 * MyDialog.parent.prototype.initialize.call( this );
2685 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2686 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2687 * this.$body.append( this.content.$element );
2689 * MyDialog.prototype.getBodyHeight = function () {
2690 * return this.content.$element.outerHeight( true );
2692 * var myDialog = new MyDialog( {
2695 * // Create and append a window manager, which opens and closes the window.
2696 * var windowManager = new OO.ui.WindowManager();
2697 * $( 'body' ).append( windowManager.$element );
2698 * windowManager.addWindows( [ myDialog ] );
2699 * // Open the window!
2700 * windowManager.openWindow( myDialog );
2702 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2706 * @extends OO.ui.Window
2707 * @mixins OO.ui.mixin.PendingElement
2710 * @param {Object} [config] Configuration options
2712 OO
.ui
.Dialog
= function OoUiDialog( config
) {
2713 // Parent constructor
2714 OO
.ui
.Dialog
.parent
.call( this, config
);
2716 // Mixin constructors
2717 OO
.ui
.mixin
.PendingElement
.call( this );
2720 this.actions
= new OO
.ui
.ActionSet();
2721 this.attachedActions
= [];
2722 this.currentAction
= null;
2723 this.onDialogKeyDownHandler
= this.onDialogKeyDown
.bind( this );
2726 this.actions
.connect( this, {
2727 click
: 'onActionClick',
2728 resize
: 'onActionResize',
2729 change
: 'onActionsChange'
2734 .addClass( 'oo-ui-dialog' )
2735 .attr( 'role', 'dialog' );
2740 OO
.inheritClass( OO
.ui
.Dialog
, OO
.ui
.Window
);
2741 OO
.mixinClass( OO
.ui
.Dialog
, OO
.ui
.mixin
.PendingElement
);
2743 /* Static Properties */
2746 * Symbolic name of dialog.
2748 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2749 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2751 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2756 * @property {string}
2758 OO
.ui
.Dialog
.static.name
= '';
2763 * The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function
2764 * that will produce a Label node or string. The title can also be specified with data passed to the
2765 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2770 * @property {jQuery|string|Function}
2772 OO
.ui
.Dialog
.static.title
= '';
2775 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2777 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2778 * value will be overriden.
2780 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2784 * @property {Object[]}
2786 OO
.ui
.Dialog
.static.actions
= [];
2789 * Close the dialog when the 'Esc' key is pressed.
2794 * @property {boolean}
2796 OO
.ui
.Dialog
.static.escapable
= true;
2801 * Handle frame document key down events.
2804 * @param {jQuery.Event} e Key down event
2806 OO
.ui
.Dialog
.prototype.onDialogKeyDown = function ( e
) {
2807 if ( e
.which
=== OO
.ui
.Keys
.ESCAPE
) {
2810 e
.stopPropagation();
2815 * Handle action resized events.
2818 * @param {OO.ui.ActionWidget} action Action that was resized
2820 OO
.ui
.Dialog
.prototype.onActionResize = function () {
2821 // Override in subclass
2825 * Handle action click events.
2828 * @param {OO.ui.ActionWidget} action Action that was clicked
2830 OO
.ui
.Dialog
.prototype.onActionClick = function ( action
) {
2831 if ( !this.isPending() ) {
2832 this.executeAction( action
.getAction() );
2837 * Handle actions change event.
2841 OO
.ui
.Dialog
.prototype.onActionsChange = function () {
2842 this.detachActions();
2843 if ( !this.isClosing() ) {
2844 this.attachActions();
2849 * Get the set of actions used by the dialog.
2851 * @return {OO.ui.ActionSet}
2853 OO
.ui
.Dialog
.prototype.getActions = function () {
2854 return this.actions
;
2858 * Get a process for taking action.
2860 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2861 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2862 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2865 * @param {string} [action] Symbolic name of action
2866 * @return {OO.ui.Process} Action process
2868 OO
.ui
.Dialog
.prototype.getActionProcess = function ( action
) {
2869 return new OO
.ui
.Process()
2870 .next( function () {
2872 // An empty action always closes the dialog without data, which should always be
2873 // safe and make no changes
2882 * @param {Object} [data] Dialog opening data
2883 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2884 * the {@link #static-title static title}
2885 * @param {Object[]} [data.actions] List of configuration options for each
2886 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2888 OO
.ui
.Dialog
.prototype.getSetupProcess = function ( data
) {
2892 return OO
.ui
.Dialog
.parent
.prototype.getSetupProcess
.call( this, data
)
2893 .next( function () {
2894 var config
= this.constructor.static,
2895 actions
= data
.actions
!== undefined ? data
.actions
: config
.actions
;
2897 this.title
.setLabel(
2898 data
.title
!== undefined ? data
.title
: this.constructor.static.title
2900 this.actions
.add( this.getActionWidgets( actions
) );
2902 if ( this.constructor.static.escapable
) {
2903 this.$element
.on( 'keydown', this.onDialogKeyDownHandler
);
2911 OO
.ui
.Dialog
.prototype.getTeardownProcess = function ( data
) {
2913 return OO
.ui
.Dialog
.parent
.prototype.getTeardownProcess
.call( this, data
)
2914 .first( function () {
2915 if ( this.constructor.static.escapable
) {
2916 this.$element
.off( 'keydown', this.onDialogKeyDownHandler
);
2919 this.actions
.clear();
2920 this.currentAction
= null;
2927 OO
.ui
.Dialog
.prototype.initialize = function () {
2931 OO
.ui
.Dialog
.parent
.prototype.initialize
.call( this );
2933 titleId
= OO
.ui
.generateElementId();
2936 this.title
= new OO
.ui
.LabelWidget( {
2941 this.$content
.addClass( 'oo-ui-dialog-content' );
2942 this.$element
.attr( 'aria-labelledby', titleId
);
2943 this.setPendingElement( this.$head
);
2947 * Get action widgets from a list of configs
2949 * @param {Object[]} actions Action widget configs
2950 * @return {OO.ui.ActionWidget[]} Action widgets
2952 OO
.ui
.Dialog
.prototype.getActionWidgets = function ( actions
) {
2953 var i
, len
, widgets
= [];
2954 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
2956 new OO
.ui
.ActionWidget( actions
[ i
] )
2963 * Attach action actions.
2967 OO
.ui
.Dialog
.prototype.attachActions = function () {
2968 // Remember the list of potentially attached actions
2969 this.attachedActions
= this.actions
.get();
2973 * Detach action actions.
2978 OO
.ui
.Dialog
.prototype.detachActions = function () {
2981 // Detach all actions that may have been previously attached
2982 for ( i
= 0, len
= this.attachedActions
.length
; i
< len
; i
++ ) {
2983 this.attachedActions
[ i
].$element
.detach();
2985 this.attachedActions
= [];
2989 * Execute an action.
2991 * @param {string} action Symbolic name of action to execute
2992 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
2994 OO
.ui
.Dialog
.prototype.executeAction = function ( action
) {
2996 this.currentAction
= action
;
2997 return this.getActionProcess( action
).execute()
2998 .always( this.popPending
.bind( this ) );
3002 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
3003 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
3004 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
3005 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
3006 * pertinent data and reused.
3008 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
3009 * `opened`, and `closing`, which represent the primary stages of the cycle:
3011 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
3012 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
3014 * - an `opening` event is emitted with an `opening` promise
3015 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
3016 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
3017 * window and its result executed
3018 * - a `setup` progress notification is emitted from the `opening` promise
3019 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
3020 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
3021 * window and its result executed
3022 * - a `ready` progress notification is emitted from the `opening` promise
3023 * - the `opening` promise is resolved with an `opened` promise
3025 * **Opened**: the window is now open.
3027 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
3028 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
3029 * to close the window.
3031 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
3032 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
3033 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
3034 * window and its result executed
3035 * - a `hold` progress notification is emitted from the `closing` promise
3036 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
3037 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
3038 * window and its result executed
3039 * - a `teardown` progress notification is emitted from the `closing` promise
3040 * - the `closing` promise is resolved. The window is now closed
3042 * See the [OOjs UI documentation on MediaWiki][1] for more information.
3044 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3047 * @extends OO.ui.Element
3048 * @mixins OO.EventEmitter
3051 * @param {Object} [config] Configuration options
3052 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
3053 * Note that window classes that are instantiated with a factory must have
3054 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
3055 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
3057 OO
.ui
.WindowManager
= function OoUiWindowManager( config
) {
3058 // Configuration initialization
3059 config
= config
|| {};
3061 // Parent constructor
3062 OO
.ui
.WindowManager
.parent
.call( this, config
);
3064 // Mixin constructors
3065 OO
.EventEmitter
.call( this );
3068 this.factory
= config
.factory
;
3069 this.modal
= config
.modal
=== undefined || !!config
.modal
;
3071 this.opening
= null;
3073 this.closing
= null;
3074 this.preparingToOpen
= null;
3075 this.preparingToClose
= null;
3076 this.currentWindow
= null;
3077 this.globalEvents
= false;
3078 this.$ariaHidden
= null;
3079 this.onWindowResizeTimeout
= null;
3080 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
3081 this.afterWindowResizeHandler
= this.afterWindowResize
.bind( this );
3085 .addClass( 'oo-ui-windowManager' )
3086 .toggleClass( 'oo-ui-windowManager-modal', this.modal
);
3091 OO
.inheritClass( OO
.ui
.WindowManager
, OO
.ui
.Element
);
3092 OO
.mixinClass( OO
.ui
.WindowManager
, OO
.EventEmitter
);
3097 * An 'opening' event is emitted when the window begins to be opened.
3100 * @param {OO.ui.Window} win Window that's being opened
3101 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
3102 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
3103 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
3104 * @param {Object} data Window opening data
3108 * A 'closing' event is emitted when the window begins to be closed.
3111 * @param {OO.ui.Window} win Window that's being closed
3112 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
3113 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
3114 * processes are complete. When the `closing` promise is resolved, the first argument of its value
3115 * is the closing data.
3116 * @param {Object} data Window closing data
3120 * A 'resize' event is emitted when a window is resized.
3123 * @param {OO.ui.Window} win Window that was resized
3126 /* Static Properties */
3129 * Map of the symbolic name of each window size and its CSS properties.
3133 * @property {Object}
3135 OO
.ui
.WindowManager
.static.sizes
= {
3149 // These can be non-numeric because they are never used in calculations
3156 * Symbolic name of the default window size.
3158 * The default size is used if the window's requested size is not recognized.
3162 * @property {string}
3164 OO
.ui
.WindowManager
.static.defaultSize
= 'medium';
3169 * Handle window resize events.
3172 * @param {jQuery.Event} e Window resize event
3174 OO
.ui
.WindowManager
.prototype.onWindowResize = function () {
3175 clearTimeout( this.onWindowResizeTimeout
);
3176 this.onWindowResizeTimeout
= setTimeout( this.afterWindowResizeHandler
, 200 );
3180 * Handle window resize events.
3183 * @param {jQuery.Event} e Window resize event
3185 OO
.ui
.WindowManager
.prototype.afterWindowResize = function () {
3186 if ( this.currentWindow
) {
3187 this.updateWindowSize( this.currentWindow
);
3192 * Check if window is opening.
3194 * @return {boolean} Window is opening
3196 OO
.ui
.WindowManager
.prototype.isOpening = function ( win
) {
3197 return win
=== this.currentWindow
&& !!this.opening
&& this.opening
.state() === 'pending';
3201 * Check if window is closing.
3203 * @return {boolean} Window is closing
3205 OO
.ui
.WindowManager
.prototype.isClosing = function ( win
) {
3206 return win
=== this.currentWindow
&& !!this.closing
&& this.closing
.state() === 'pending';
3210 * Check if window is opened.
3212 * @return {boolean} Window is opened
3214 OO
.ui
.WindowManager
.prototype.isOpened = function ( win
) {
3215 return win
=== this.currentWindow
&& !!this.opened
&& this.opened
.state() === 'pending';
3219 * Check if a window is being managed.
3221 * @param {OO.ui.Window} win Window to check
3222 * @return {boolean} Window is being managed
3224 OO
.ui
.WindowManager
.prototype.hasWindow = function ( win
) {
3227 for ( name
in this.windows
) {
3228 if ( this.windows
[ name
] === win
) {
3237 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
3239 * @param {OO.ui.Window} win Window being opened
3240 * @param {Object} [data] Window opening data
3241 * @return {number} Milliseconds to wait
3243 OO
.ui
.WindowManager
.prototype.getSetupDelay = function () {
3248 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
3250 * @param {OO.ui.Window} win Window being opened
3251 * @param {Object} [data] Window opening data
3252 * @return {number} Milliseconds to wait
3254 OO
.ui
.WindowManager
.prototype.getReadyDelay = function () {
3259 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
3261 * @param {OO.ui.Window} win Window being closed
3262 * @param {Object} [data] Window closing data
3263 * @return {number} Milliseconds to wait
3265 OO
.ui
.WindowManager
.prototype.getHoldDelay = function () {
3270 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
3271 * executing the ‘teardown’ process.
3273 * @param {OO.ui.Window} win Window being closed
3274 * @param {Object} [data] Window closing data
3275 * @return {number} Milliseconds to wait
3277 OO
.ui
.WindowManager
.prototype.getTeardownDelay = function () {
3278 return this.modal
? 250 : 0;
3282 * Get a window by its symbolic name.
3284 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
3285 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
3286 * for more information about using factories.
3287 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3289 * @param {string} name Symbolic name of the window
3290 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
3291 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
3292 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
3294 OO
.ui
.WindowManager
.prototype.getWindow = function ( name
) {
3295 var deferred
= $.Deferred(),
3296 win
= this.windows
[ name
];
3298 if ( !( win
instanceof OO
.ui
.Window
) ) {
3299 if ( this.factory
) {
3300 if ( !this.factory
.lookup( name
) ) {
3301 deferred
.reject( new OO
.ui
.Error(
3302 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
3305 win
= this.factory
.create( name
);
3306 this.addWindows( [ win
] );
3307 deferred
.resolve( win
);
3310 deferred
.reject( new OO
.ui
.Error(
3311 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
3315 deferred
.resolve( win
);
3318 return deferred
.promise();
3322 * Get current window.
3324 * @return {OO.ui.Window|null} Currently opening/opened/closing window
3326 OO
.ui
.WindowManager
.prototype.getCurrentWindow = function () {
3327 return this.currentWindow
;
3333 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
3334 * @param {Object} [data] Window opening data
3335 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3336 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3339 OO
.ui
.WindowManager
.prototype.openWindow = function ( win
, data
) {
3341 opening
= $.Deferred();
3343 // Argument handling
3344 if ( typeof win
=== 'string' ) {
3345 return this.getWindow( win
).then( function ( win
) {
3346 return manager
.openWindow( win
, data
);
3351 if ( !this.hasWindow( win
) ) {
3352 opening
.reject( new OO
.ui
.Error(
3353 'Cannot open window: window is not attached to manager'
3355 } else if ( this.preparingToOpen
|| this.opening
|| this.opened
) {
3356 opening
.reject( new OO
.ui
.Error(
3357 'Cannot open window: another window is opening or open'
3362 if ( opening
.state() !== 'rejected' ) {
3363 // If a window is currently closing, wait for it to complete
3364 this.preparingToOpen
= $.when( this.closing
);
3365 // Ensure handlers get called after preparingToOpen is set
3366 this.preparingToOpen
.done( function () {
3367 if ( manager
.modal
) {
3368 manager
.toggleGlobalEvents( true );
3369 manager
.toggleAriaIsolation( true );
3371 manager
.currentWindow
= win
;
3372 manager
.opening
= opening
;
3373 manager
.preparingToOpen
= null;
3374 manager
.emit( 'opening', win
, opening
, data
);
3375 setTimeout( function () {
3376 win
.setup( data
).then( function () {
3377 manager
.updateWindowSize( win
);
3378 manager
.opening
.notify( { state
: 'setup' } );
3379 setTimeout( function () {
3380 win
.ready( data
).then( function () {
3381 manager
.opening
.notify( { state
: 'ready' } );
3382 manager
.opening
= null;
3383 manager
.opened
= $.Deferred();
3384 opening
.resolve( manager
.opened
.promise(), data
);
3386 }, manager
.getReadyDelay() );
3388 }, manager
.getSetupDelay() );
3392 return opening
.promise();
3398 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3399 * @param {Object} [data] Window closing data
3400 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3401 * See {@link #event-closing 'closing' event} for more information about closing promises.
3402 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3405 OO
.ui
.WindowManager
.prototype.closeWindow = function ( win
, data
) {
3407 closing
= $.Deferred(),
3410 // Argument handling
3411 if ( typeof win
=== 'string' ) {
3412 win
= this.windows
[ win
];
3413 } else if ( !this.hasWindow( win
) ) {
3419 closing
.reject( new OO
.ui
.Error(
3420 'Cannot close window: window is not attached to manager'
3422 } else if ( win
!== this.currentWindow
) {
3423 closing
.reject( new OO
.ui
.Error(
3424 'Cannot close window: window already closed with different data'
3426 } else if ( this.preparingToClose
|| this.closing
) {
3427 closing
.reject( new OO
.ui
.Error(
3428 'Cannot close window: window already closing with different data'
3433 if ( closing
.state() !== 'rejected' ) {
3434 // If the window is currently opening, close it when it's done
3435 this.preparingToClose
= $.when( this.opening
);
3436 // Ensure handlers get called after preparingToClose is set
3437 this.preparingToClose
.done( function () {
3438 manager
.closing
= closing
;
3439 manager
.preparingToClose
= null;
3440 manager
.emit( 'closing', win
, closing
, data
);
3441 opened
= manager
.opened
;
3442 manager
.opened
= null;
3443 opened
.resolve( closing
.promise(), data
);
3444 setTimeout( function () {
3445 win
.hold( data
).then( function () {
3446 closing
.notify( { state
: 'hold' } );
3447 setTimeout( function () {
3448 win
.teardown( data
).then( function () {
3449 closing
.notify( { state
: 'teardown' } );
3450 if ( manager
.modal
) {
3451 manager
.toggleGlobalEvents( false );
3452 manager
.toggleAriaIsolation( false );
3454 manager
.closing
= null;
3455 manager
.currentWindow
= null;
3456 closing
.resolve( data
);
3458 }, manager
.getTeardownDelay() );
3460 }, manager
.getHoldDelay() );
3464 return closing
.promise();
3468 * Add windows to the window manager.
3470 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3471 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3472 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3474 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3475 * by reference, symbolic name, or explicitly defined symbolic names.
3476 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3477 * explicit nor a statically configured symbolic name.
3479 OO
.ui
.WindowManager
.prototype.addWindows = function ( windows
) {
3480 var i
, len
, win
, name
, list
;
3482 if ( Array
.isArray( windows
) ) {
3483 // Convert to map of windows by looking up symbolic names from static configuration
3485 for ( i
= 0, len
= windows
.length
; i
< len
; i
++ ) {
3486 name
= windows
[ i
].constructor.static.name
;
3487 if ( typeof name
!== 'string' ) {
3488 throw new Error( 'Cannot add window' );
3490 list
[ name
] = windows
[ i
];
3492 } else if ( OO
.isPlainObject( windows
) ) {
3497 for ( name
in list
) {
3499 this.windows
[ name
] = win
.toggle( false );
3500 this.$element
.append( win
.$element
);
3501 win
.setManager( this );
3506 * Remove the specified windows from the windows manager.
3508 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3509 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3510 * longer listens to events, use the #destroy method.
3512 * @param {string[]} names Symbolic names of windows to remove
3513 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3514 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3516 OO
.ui
.WindowManager
.prototype.removeWindows = function ( names
) {
3517 var i
, len
, win
, name
, cleanupWindow
,
3520 cleanup = function ( name
, win
) {
3521 delete manager
.windows
[ name
];
3522 win
.$element
.detach();
3525 for ( i
= 0, len
= names
.length
; i
< len
; i
++ ) {
3527 win
= this.windows
[ name
];
3529 throw new Error( 'Cannot remove window' );
3531 cleanupWindow
= cleanup
.bind( null, name
, win
);
3532 promises
.push( this.closeWindow( name
).then( cleanupWindow
, cleanupWindow
) );
3535 return $.when
.apply( $, promises
);
3539 * Remove all windows from the window manager.
3541 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3542 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3543 * To remove just a subset of windows, use the #removeWindows method.
3545 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3547 OO
.ui
.WindowManager
.prototype.clearWindows = function () {
3548 return this.removeWindows( Object
.keys( this.windows
) );
3552 * Set dialog size. In general, this method should not be called directly.
3554 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3558 OO
.ui
.WindowManager
.prototype.updateWindowSize = function ( win
) {
3561 // Bypass for non-current, and thus invisible, windows
3562 if ( win
!== this.currentWindow
) {
3566 isFullscreen
= win
.getSize() === 'full';
3568 this.$element
.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen
);
3569 this.$element
.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen
);
3570 win
.setDimensions( win
.getSizeProperties() );
3572 this.emit( 'resize', win
);
3578 * Bind or unbind global events for scrolling.
3581 * @param {boolean} [on] Bind global events
3584 OO
.ui
.WindowManager
.prototype.toggleGlobalEvents = function ( on
) {
3585 var scrollWidth
, bodyMargin
,
3586 $body
= $( this.getElementDocument().body
),
3587 // We could have multiple window managers open so only modify
3588 // the body css at the bottom of the stack
3589 stackDepth
= $body
.data( 'windowManagerGlobalEvents' ) || 0 ;
3591 on
= on
=== undefined ? !!this.globalEvents
: !!on
;
3594 if ( !this.globalEvents
) {
3595 $( this.getElementWindow() ).on( {
3596 // Start listening for top-level window dimension changes
3597 'orientationchange resize': this.onWindowResizeHandler
3599 if ( stackDepth
=== 0 ) {
3600 scrollWidth
= window
.innerWidth
- document
.documentElement
.clientWidth
;
3601 bodyMargin
= parseFloat( $body
.css( 'margin-right' ) ) || 0;
3604 'margin-right': bodyMargin
+ scrollWidth
3608 this.globalEvents
= true;
3610 } else if ( this.globalEvents
) {
3611 $( this.getElementWindow() ).off( {
3612 // Stop listening for top-level window dimension changes
3613 'orientationchange resize': this.onWindowResizeHandler
3616 if ( stackDepth
=== 0 ) {
3622 this.globalEvents
= false;
3624 $body
.data( 'windowManagerGlobalEvents', stackDepth
);
3630 * Toggle screen reader visibility of content other than the window manager.
3633 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3636 OO
.ui
.WindowManager
.prototype.toggleAriaIsolation = function ( isolate
) {
3637 isolate
= isolate
=== undefined ? !this.$ariaHidden
: !!isolate
;
3640 if ( !this.$ariaHidden
) {
3641 // Hide everything other than the window manager from screen readers
3642 this.$ariaHidden
= $( 'body' )
3644 .not( this.$element
.parentsUntil( 'body' ).last() )
3645 .attr( 'aria-hidden', '' );
3647 } else if ( this.$ariaHidden
) {
3648 // Restore screen reader visibility
3649 this.$ariaHidden
.removeAttr( 'aria-hidden' );
3650 this.$ariaHidden
= null;
3657 * Destroy the window manager.
3659 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3660 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3663 OO
.ui
.WindowManager
.prototype.destroy = function () {
3664 this.toggleGlobalEvents( false );
3665 this.toggleAriaIsolation( false );
3666 this.clearWindows();
3667 this.$element
.remove();
3671 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3672 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3673 * appearance and functionality of the error interface.
3675 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3676 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3677 * that initiated the failed process will be disabled.
3679 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3682 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3684 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3689 * @param {string|jQuery} message Description of error
3690 * @param {Object} [config] Configuration options
3691 * @cfg {boolean} [recoverable=true] Error is recoverable.
3692 * By default, errors are recoverable, and users can try the process again.
3693 * @cfg {boolean} [warning=false] Error is a warning.
3694 * If the error is a warning, the error interface will include a
3695 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3696 * is not triggered a second time if the user chooses to continue.
3698 OO
.ui
.Error
= function OoUiError( message
, config
) {
3699 // Allow passing positional parameters inside the config object
3700 if ( OO
.isPlainObject( message
) && config
=== undefined ) {
3702 message
= config
.message
;
3705 // Configuration initialization
3706 config
= config
|| {};
3709 this.message
= message
instanceof jQuery
? message
: String( message
);
3710 this.recoverable
= config
.recoverable
=== undefined || !!config
.recoverable
;
3711 this.warning
= !!config
.warning
;
3716 OO
.initClass( OO
.ui
.Error
);
3721 * Check if the error is recoverable.
3723 * If the error is recoverable, users are able to try the process again.
3725 * @return {boolean} Error is recoverable
3727 OO
.ui
.Error
.prototype.isRecoverable = function () {
3728 return this.recoverable
;
3732 * Check if the error is a warning.
3734 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3736 * @return {boolean} Error is warning
3738 OO
.ui
.Error
.prototype.isWarning = function () {
3739 return this.warning
;
3743 * Get error message as DOM nodes.
3745 * @return {jQuery} Error message in DOM nodes
3747 OO
.ui
.Error
.prototype.getMessage = function () {
3748 return this.message
instanceof jQuery
?
3749 this.message
.clone() :
3750 $( '<div>' ).text( this.message
).contents();
3754 * Get the error message text.
3756 * @return {string} Error message
3758 OO
.ui
.Error
.prototype.getMessageText = function () {
3759 return this.message
instanceof jQuery
? this.message
.text() : this.message
;
3763 * Wraps an HTML snippet for use with configuration values which default
3764 * to strings. This bypasses the default html-escaping done to string
3770 * @param {string} [content] HTML content
3772 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
3774 this.content
= content
;
3779 OO
.initClass( OO
.ui
.HtmlSnippet
);
3786 * @return {string} Unchanged HTML snippet.
3788 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
3789 return this.content
;
3793 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3796 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3797 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3798 * or stop if the promise is rejected.
3799 * - **function**: the process will execute the function. The process will stop if the function returns
3800 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3801 * will wait for that number of milliseconds before proceeding.
3803 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3804 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3805 * its remaining steps will not be performed.
3810 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3811 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3812 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3813 * a number or promise.
3814 * @return {Object} Step object, with `callback` and `context` properties
3816 OO
.ui
.Process = function ( step
, context
) {
3821 if ( step
!== undefined ) {
3822 this.next( step
, context
);
3828 OO
.initClass( OO
.ui
.Process
);
3833 * Start the process.
3835 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
3836 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
3837 * and any remaining steps are not performed.
3839 OO
.ui
.Process
.prototype.execute = function () {
3840 var i
, len
, promise
;
3843 * Continue execution.
3846 * @param {Array} step A function and the context it should be called in
3847 * @return {Function} Function that continues the process
3849 function proceed( step
) {
3850 return function () {
3851 // Execute step in the correct context
3853 result
= step
.callback
.call( step
.context
);
3855 if ( result
=== false ) {
3856 // Use rejected promise for boolean false results
3857 return $.Deferred().reject( [] ).promise();
3859 if ( typeof result
=== 'number' ) {
3861 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3863 // Use a delayed promise for numbers, expecting them to be in milliseconds
3864 deferred
= $.Deferred();
3865 setTimeout( deferred
.resolve
, result
);
3866 return deferred
.promise();
3868 if ( result
instanceof OO
.ui
.Error
) {
3869 // Use rejected promise for error
3870 return $.Deferred().reject( [ result
] ).promise();
3872 if ( Array
.isArray( result
) && result
.length
&& result
[ 0 ] instanceof OO
.ui
.Error
) {
3873 // Use rejected promise for list of errors
3874 return $.Deferred().reject( result
).promise();
3876 // Duck-type the object to see if it can produce a promise
3877 if ( result
&& $.isFunction( result
.promise
) ) {
3878 // Use a promise generated from the result
3879 return result
.promise();
3881 // Use resolved promise for other results
3882 return $.Deferred().resolve().promise();
3886 if ( this.steps
.length
) {
3887 // Generate a chain reaction of promises
3888 promise
= proceed( this.steps
[ 0 ] )();
3889 for ( i
= 1, len
= this.steps
.length
; i
< len
; i
++ ) {
3890 promise
= promise
.then( proceed( this.steps
[ i
] ) );
3893 promise
= $.Deferred().resolve().promise();
3900 * Create a process step.
3903 * @param {number|jQuery.Promise|Function} step
3905 * - Number of milliseconds to wait before proceeding
3906 * - Promise that must be resolved before proceeding
3907 * - Function to execute
3908 * - If the function returns a boolean false the process will stop
3909 * - If the function returns a promise, the process will continue to the next
3910 * step when the promise is resolved or stop if the promise is rejected
3911 * - If the function returns a number, the process will wait for that number of
3912 * milliseconds before proceeding
3913 * @param {Object} [context=null] Execution context of the function. The context is
3914 * ignored if the step is a number or promise.
3915 * @return {Object} Step object, with `callback` and `context` properties
3917 OO
.ui
.Process
.prototype.createStep = function ( step
, context
) {
3918 if ( typeof step
=== 'number' || $.isFunction( step
.promise
) ) {
3920 callback: function () {
3926 if ( $.isFunction( step
) ) {
3932 throw new Error( 'Cannot create process step: number, promise or function expected' );
3936 * Add step to the beginning of the process.
3938 * @inheritdoc #createStep
3939 * @return {OO.ui.Process} this
3942 OO
.ui
.Process
.prototype.first = function ( step
, context
) {
3943 this.steps
.unshift( this.createStep( step
, context
) );
3948 * Add step to the end of the process.
3950 * @inheritdoc #createStep
3951 * @return {OO.ui.Process} this
3954 OO
.ui
.Process
.prototype.next = function ( step
, context
) {
3955 this.steps
.push( this.createStep( step
, context
) );
3960 * A ToolFactory creates tools on demand. All tools ({@link OO.ui.Tool Tools}, {@link OO.ui.PopupTool PopupTools},
3961 * and {@link OO.ui.ToolGroupTool ToolGroupTools}) must be registered with a tool factory. Tools are
3962 * registered by their symbolic name. See {@link OO.ui.Toolbar toolbars} for an example.
3964 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
3966 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
3969 * @extends OO.Factory
3972 OO
.ui
.ToolFactory
= function OoUiToolFactory() {
3973 // Parent constructor
3974 OO
.ui
.ToolFactory
.parent
.call( this );
3979 OO
.inheritClass( OO
.ui
.ToolFactory
, OO
.Factory
);
3984 * Get tools from the factory
3986 * @param {Array} include Included tools
3987 * @param {Array} exclude Excluded tools
3988 * @param {Array} promote Promoted tools
3989 * @param {Array} demote Demoted tools
3990 * @return {string[]} List of tools
3992 OO
.ui
.ToolFactory
.prototype.getTools = function ( include
, exclude
, promote
, demote
) {
3993 var i
, len
, included
, promoted
, demoted
,
3997 // Collect included and not excluded tools
3998 included
= OO
.simpleArrayDifference( this.extract( include
), this.extract( exclude
) );
4001 promoted
= this.extract( promote
, used
);
4002 demoted
= this.extract( demote
, used
);
4005 for ( i
= 0, len
= included
.length
; i
< len
; i
++ ) {
4006 if ( !used
[ included
[ i
] ] ) {
4007 auto
.push( included
[ i
] );
4011 return promoted
.concat( auto
).concat( demoted
);
4015 * Get a flat list of names from a list of names or groups.
4017 * Tools can be specified in the following ways:
4019 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
4020 * - All tools in a group: `{ group: 'group-name' }`
4021 * - All tools: `'*'`
4024 * @param {Array|string} collection List of tools
4025 * @param {Object} [used] Object with names that should be skipped as properties; extracted
4026 * names will be added as properties
4027 * @return {string[]} List of extracted names
4029 OO
.ui
.ToolFactory
.prototype.extract = function ( collection
, used
) {
4030 var i
, len
, item
, name
, tool
,
4033 if ( collection
=== '*' ) {
4034 for ( name
in this.registry
) {
4035 tool
= this.registry
[ name
];
4037 // Only add tools by group name when auto-add is enabled
4038 tool
.static.autoAddToCatchall
&&
4039 // Exclude already used tools
4040 ( !used
|| !used
[ name
] )
4044 used
[ name
] = true;
4048 } else if ( Array
.isArray( collection
) ) {
4049 for ( i
= 0, len
= collection
.length
; i
< len
; i
++ ) {
4050 item
= collection
[ i
];
4051 // Allow plain strings as shorthand for named tools
4052 if ( typeof item
=== 'string' ) {
4053 item
= { name
: item
};
4055 if ( OO
.isPlainObject( item
) ) {
4057 for ( name
in this.registry
) {
4058 tool
= this.registry
[ name
];
4060 // Include tools with matching group
4061 tool
.static.group
=== item
.group
&&
4062 // Only add tools by group name when auto-add is enabled
4063 tool
.static.autoAddToGroup
&&
4064 // Exclude already used tools
4065 ( !used
|| !used
[ name
] )
4069 used
[ name
] = true;
4073 // Include tools with matching name and exclude already used tools
4074 } else if ( item
.name
&& ( !used
|| !used
[ item
.name
] ) ) {
4075 names
.push( item
.name
);
4077 used
[ item
.name
] = true;
4087 * ToolGroupFactories create {@link OO.ui.ToolGroup toolgroups} on demand. The toolgroup classes must
4088 * specify a symbolic name and be registered with the factory. The following classes are registered by
4091 * - {@link OO.ui.BarToolGroup BarToolGroups} (‘bar’)
4092 * - {@link OO.ui.MenuToolGroup MenuToolGroups} (‘menu’)
4093 * - {@link OO.ui.ListToolGroup ListToolGroups} (‘list’)
4095 * See {@link OO.ui.Toolbar toolbars} for an example.
4097 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4099 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4101 * @extends OO.Factory
4104 OO
.ui
.ToolGroupFactory
= function OoUiToolGroupFactory() {
4105 var i
, l
, defaultClasses
;
4106 // Parent constructor
4107 OO
.Factory
.call( this );
4109 defaultClasses
= this.constructor.static.getDefaultClasses();
4111 // Register default toolgroups
4112 for ( i
= 0, l
= defaultClasses
.length
; i
< l
; i
++ ) {
4113 this.register( defaultClasses
[ i
] );
4119 OO
.inheritClass( OO
.ui
.ToolGroupFactory
, OO
.Factory
);
4121 /* Static Methods */
4124 * Get a default set of classes to be registered on construction.
4126 * @return {Function[]} Default classes
4128 OO
.ui
.ToolGroupFactory
.static.getDefaultClasses = function () {
4131 OO
.ui
.ListToolGroup
,
4143 * @param {Object} [config] Configuration options
4145 OO
.ui
.Theme
= function OoUiTheme( config
) {
4146 // Configuration initialization
4147 config
= config
|| {};
4152 OO
.initClass( OO
.ui
.Theme
);
4157 * Get a list of classes to be applied to a widget.
4159 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
4160 * otherwise state transitions will not work properly.
4162 * @param {OO.ui.Element} element Element for which to get classes
4163 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4165 OO
.ui
.Theme
.prototype.getElementClasses = function ( /* element */ ) {
4166 return { on
: [], off
: [] };
4170 * Update CSS classes provided by the theme.
4172 * For elements with theme logic hooks, this should be called any time there's a state change.
4174 * @param {OO.ui.Element} element Element for which to update classes
4175 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4177 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
4178 var $elements
= $( [] ),
4179 classes
= this.getElementClasses( element
);
4181 if ( element
.$icon
) {
4182 $elements
= $elements
.add( element
.$icon
);
4184 if ( element
.$indicator
) {
4185 $elements
= $elements
.add( element
.$indicator
);
4189 .removeClass( classes
.off
.join( ' ' ) )
4190 .addClass( classes
.on
.join( ' ' ) );
4194 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
4195 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
4196 * order in which users will navigate through the focusable elements via the "tab" key.
4199 * // TabIndexedElement is mixed into the ButtonWidget class
4200 * // to provide a tabIndex property.
4201 * var button1 = new OO.ui.ButtonWidget( {
4205 * var button2 = new OO.ui.ButtonWidget( {
4209 * var button3 = new OO.ui.ButtonWidget( {
4213 * var button4 = new OO.ui.ButtonWidget( {
4217 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
4223 * @param {Object} [config] Configuration options
4224 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
4225 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
4226 * functionality will be applied to it instead.
4227 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
4228 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
4229 * to remove the element from the tab-navigation flow.
4231 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
4232 // Configuration initialization
4233 config
= $.extend( { tabIndex
: 0 }, config
);
4236 this.$tabIndexed
= null;
4237 this.tabIndex
= null;
4240 this.connect( this, { disable
: 'onTabIndexedElementDisable' } );
4243 this.setTabIndex( config
.tabIndex
);
4244 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
4249 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
4254 * Set the element that should use the tabindex functionality.
4256 * This method is used to retarget a tabindex mixin so that its functionality applies
4257 * to the specified element. If an element is currently using the functionality, the mixin’s
4258 * effect on that element is removed before the new element is set up.
4260 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
4263 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
4264 var tabIndex
= this.tabIndex
;
4265 // Remove attributes from old $tabIndexed
4266 this.setTabIndex( null );
4267 // Force update of new $tabIndexed
4268 this.$tabIndexed
= $tabIndexed
;
4269 this.tabIndex
= tabIndex
;
4270 return this.updateTabIndex();
4274 * Set the value of the tabindex.
4276 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
4279 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
4280 tabIndex
= typeof tabIndex
=== 'number' ? tabIndex
: null;
4282 if ( this.tabIndex
!== tabIndex
) {
4283 this.tabIndex
= tabIndex
;
4284 this.updateTabIndex();
4291 * Update the `tabindex` attribute, in case of changes to tab index or
4297 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
4298 if ( this.$tabIndexed
) {
4299 if ( this.tabIndex
!== null ) {
4300 // Do not index over disabled elements
4301 this.$tabIndexed
.attr( {
4302 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
4303 // Support: ChromeVox and NVDA
4304 // These do not seem to inherit aria-disabled from parent elements
4305 'aria-disabled': this.isDisabled().toString()
4308 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
4315 * Handle disable events.
4318 * @param {boolean} disabled Element is disabled
4320 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
4321 this.updateTabIndex();
4325 * Get the value of the tabindex.
4327 * @return {number|null} Tabindex value
4329 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
4330 return this.tabIndex
;
4334 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
4335 * interface element that can be configured with access keys for accessibility.
4336 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
4338 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
4343 * @param {Object} [config] Configuration options
4344 * @cfg {jQuery} [$button] The button element created by the class.
4345 * If this configuration is omitted, the button element will use a generated `<a>`.
4346 * @cfg {boolean} [framed=true] Render the button with a frame
4348 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
4349 // Configuration initialization
4350 config
= config
|| {};
4353 this.$button
= null;
4355 this.active
= false;
4356 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
4357 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
4358 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
4359 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
4360 this.onClickHandler
= this.onClick
.bind( this );
4361 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
4364 this.$element
.addClass( 'oo-ui-buttonElement' );
4365 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
4366 this.setButtonElement( config
.$button
|| $( '<a>' ) );
4371 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
4373 /* Static Properties */
4376 * Cancel mouse down events.
4378 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4379 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4380 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4385 * @property {boolean}
4387 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
4392 * A 'click' event is emitted when the button element is clicked.
4400 * Set the button element.
4402 * This method is used to retarget a button mixin so that its functionality applies to
4403 * the specified button element instead of the one created by the class. If a button element
4404 * is already set, the method will remove the mixin’s effect on that element.
4406 * @param {jQuery} $button Element to use as button
4408 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
4409 if ( this.$button
) {
4411 .removeClass( 'oo-ui-buttonElement-button' )
4412 .removeAttr( 'role accesskey' )
4414 mousedown
: this.onMouseDownHandler
,
4415 keydown
: this.onKeyDownHandler
,
4416 click
: this.onClickHandler
,
4417 keypress
: this.onKeyPressHandler
4421 this.$button
= $button
4422 .addClass( 'oo-ui-buttonElement-button' )
4423 .attr( { role
: 'button' } )
4425 mousedown
: this.onMouseDownHandler
,
4426 keydown
: this.onKeyDownHandler
,
4427 click
: this.onClickHandler
,
4428 keypress
: this.onKeyPressHandler
4433 * Handles mouse down events.
4436 * @param {jQuery.Event} e Mouse down event
4438 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
4439 if ( this.isDisabled() || e
.which
!== 1 ) {
4442 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4443 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4444 // reliably remove the pressed class
4445 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler
);
4446 // Prevent change of focus unless specifically configured otherwise
4447 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
4453 * Handles mouse up events.
4456 * @param {jQuery.Event} e Mouse up event
4458 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp = function ( e
) {
4459 if ( this.isDisabled() || e
.which
!== 1 ) {
4462 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4463 // Stop listening for mouseup, since we only needed this once
4464 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler
);
4468 * Handles mouse click events.
4471 * @param {jQuery.Event} e Mouse click event
4474 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
4475 if ( !this.isDisabled() && e
.which
=== 1 ) {
4476 if ( this.emit( 'click' ) ) {
4483 * Handles key down events.
4486 * @param {jQuery.Event} e Key down event
4488 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
4489 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4492 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4493 // Run the keyup handler no matter where the key is when the button is let go, so we can
4494 // reliably remove the pressed class
4495 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler
);
4499 * Handles key up events.
4502 * @param {jQuery.Event} e Key up event
4504 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyUp = function ( e
) {
4505 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4508 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4509 // Stop listening for keyup, since we only needed this once
4510 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler
);
4514 * Handles key press events.
4517 * @param {jQuery.Event} e Key press event
4520 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
4521 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
4522 if ( this.emit( 'click' ) ) {
4529 * Check if button has a frame.
4531 * @return {boolean} Button is framed
4533 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
4538 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4540 * @param {boolean} [framed] Make button framed, omit to toggle
4543 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
4544 framed
= framed
=== undefined ? !this.framed
: !!framed
;
4545 if ( framed
!== this.framed
) {
4546 this.framed
= framed
;
4548 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
4549 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
4550 this.updateThemeClasses();
4557 * Set the button to its 'active' state.
4559 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4560 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4561 * for other button types.
4563 * @param {boolean} [value] Make button active
4566 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
4567 this.$element
.toggleClass( 'oo-ui-buttonElement-active', !!value
);
4572 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4573 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4574 * items from the group is done through the interface the class provides.
4575 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4577 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4583 * @param {Object} [config] Configuration options
4584 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4585 * is omitted, the group element will use a generated `<div>`.
4587 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
4588 // Configuration initialization
4589 config
= config
|| {};
4594 this.aggregateItemEvents
= {};
4597 this.setGroupElement( config
.$group
|| $( '<div>' ) );
4603 * Set the group element.
4605 * If an element is already set, items will be moved to the new element.
4607 * @param {jQuery} $group Element to use as group
4609 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
4612 this.$group
= $group
;
4613 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4614 this.$group
.append( this.items
[ i
].$element
);
4619 * Check if a group contains no items.
4621 * @return {boolean} Group is empty
4623 OO
.ui
.mixin
.GroupElement
.prototype.isEmpty = function () {
4624 return !this.items
.length
;
4628 * Get all items in the group.
4630 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4631 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4634 * @return {OO.ui.Element[]} An array of items.
4636 OO
.ui
.mixin
.GroupElement
.prototype.getItems = function () {
4637 return this.items
.slice( 0 );
4641 * Get an item by its data.
4643 * Only the first item with matching data will be returned. To return all matching items,
4644 * use the #getItemsFromData method.
4646 * @param {Object} data Item data to search for
4647 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4649 OO
.ui
.mixin
.GroupElement
.prototype.getItemFromData = function ( data
) {
4651 hash
= OO
.getHash( data
);
4653 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4654 item
= this.items
[ i
];
4655 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4664 * Get items by their data.
4666 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4668 * @param {Object} data Item data to search for
4669 * @return {OO.ui.Element[]} Items with equivalent data
4671 OO
.ui
.mixin
.GroupElement
.prototype.getItemsFromData = function ( data
) {
4673 hash
= OO
.getHash( data
),
4676 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4677 item
= this.items
[ i
];
4678 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4687 * Aggregate the events emitted by the group.
4689 * When events are aggregated, the group will listen to all contained items for the event,
4690 * and then emit the event under a new name. The new event will contain an additional leading
4691 * parameter containing the item that emitted the original event. Other arguments emitted from
4692 * the original event are passed through.
4694 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4695 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4696 * A `null` value will remove aggregated events.
4698 * @throws {Error} An error is thrown if aggregation already exists.
4700 OO
.ui
.mixin
.GroupElement
.prototype.aggregate = function ( events
) {
4701 var i
, len
, item
, add
, remove
, itemEvent
, groupEvent
;
4703 for ( itemEvent
in events
) {
4704 groupEvent
= events
[ itemEvent
];
4706 // Remove existing aggregated event
4707 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4708 // Don't allow duplicate aggregations
4710 throw new Error( 'Duplicate item event aggregation for ' + itemEvent
);
4712 // Remove event aggregation from existing items
4713 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4714 item
= this.items
[ i
];
4715 if ( item
.connect
&& item
.disconnect
) {
4717 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4718 item
.disconnect( this, remove
);
4721 // Prevent future items from aggregating event
4722 delete this.aggregateItemEvents
[ itemEvent
];
4725 // Add new aggregate event
4727 // Make future items aggregate event
4728 this.aggregateItemEvents
[ itemEvent
] = groupEvent
;
4729 // Add event aggregation to existing items
4730 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4731 item
= this.items
[ i
];
4732 if ( item
.connect
&& item
.disconnect
) {
4734 add
[ itemEvent
] = [ 'emit', groupEvent
, item
];
4735 item
.connect( this, add
);
4743 * Add items to the group.
4745 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4746 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4748 * @param {OO.ui.Element[]} items An array of items to add to the group
4749 * @param {number} [index] Index of the insertion point
4752 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
4753 var i
, len
, item
, event
, events
, currentIndex
,
4756 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4759 // Check if item exists then remove it first, effectively "moving" it
4760 currentIndex
= this.items
.indexOf( item
);
4761 if ( currentIndex
>= 0 ) {
4762 this.removeItems( [ item
] );
4763 // Adjust index to compensate for removal
4764 if ( currentIndex
< index
) {
4769 if ( item
.connect
&& item
.disconnect
&& !$.isEmptyObject( this.aggregateItemEvents
) ) {
4771 for ( event
in this.aggregateItemEvents
) {
4772 events
[ event
] = [ 'emit', this.aggregateItemEvents
[ event
], item
];
4774 item
.connect( this, events
);
4776 item
.setElementGroup( this );
4777 itemElements
.push( item
.$element
.get( 0 ) );
4780 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
4781 this.$group
.append( itemElements
);
4782 this.items
.push
.apply( this.items
, items
);
4783 } else if ( index
=== 0 ) {
4784 this.$group
.prepend( itemElements
);
4785 this.items
.unshift
.apply( this.items
, items
);
4787 this.items
[ index
].$element
.before( itemElements
);
4788 this.items
.splice
.apply( this.items
, [ index
, 0 ].concat( items
) );
4795 * Remove the specified items from a group.
4797 * Removed items are detached (not removed) from the DOM so that they may be reused.
4798 * To remove all items from a group, you may wish to use the #clearItems method instead.
4800 * @param {OO.ui.Element[]} items An array of items to remove
4803 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
4804 var i
, len
, item
, index
, remove
, itemEvent
;
4806 // Remove specific items
4807 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4809 index
= this.items
.indexOf( item
);
4810 if ( index
!== -1 ) {
4812 item
.connect
&& item
.disconnect
&&
4813 !$.isEmptyObject( this.aggregateItemEvents
)
4816 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4817 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4819 item
.disconnect( this, remove
);
4821 item
.setElementGroup( null );
4822 this.items
.splice( index
, 1 );
4823 item
.$element
.detach();
4831 * Clear all items from the group.
4833 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4834 * To remove only a subset of items from a group, use the #removeItems method.
4838 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
4839 var i
, len
, item
, remove
, itemEvent
;
4842 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4843 item
= this.items
[ i
];
4845 item
.connect
&& item
.disconnect
&&
4846 !$.isEmptyObject( this.aggregateItemEvents
)
4849 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4850 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4852 item
.disconnect( this, remove
);
4854 item
.setElementGroup( null );
4855 item
.$element
.detach();
4863 * DraggableElement is a mixin class used to create elements that can be clicked
4864 * and dragged by a mouse to a new position within a group. This class must be used
4865 * in conjunction with OO.ui.mixin.DraggableGroupElement, which provides a container for
4866 * the draggable elements.
4873 OO
.ui
.mixin
.DraggableElement
= function OoUiMixinDraggableElement() {
4877 // Initialize and events
4879 .attr( 'draggable', true )
4880 .addClass( 'oo-ui-draggableElement' )
4882 dragstart
: this.onDragStart
.bind( this ),
4883 dragover
: this.onDragOver
.bind( this ),
4884 dragend
: this.onDragEnd
.bind( this ),
4885 drop
: this.onDrop
.bind( this )
4889 OO
.initClass( OO
.ui
.mixin
.DraggableElement
);
4896 * A dragstart event is emitted when the user clicks and begins dragging an item.
4897 * @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse.
4902 * A dragend event is emitted when the user drags an item and releases the mouse,
4903 * thus terminating the drag operation.
4908 * A drop event is emitted when the user drags an item and then releases the mouse button
4909 * over a valid target.
4912 /* Static Properties */
4915 * @inheritdoc OO.ui.mixin.ButtonElement
4917 OO
.ui
.mixin
.DraggableElement
.static.cancelButtonMouseDownEvents
= false;
4922 * Respond to dragstart event.
4925 * @param {jQuery.Event} event jQuery event
4928 OO
.ui
.mixin
.DraggableElement
.prototype.onDragStart = function ( e
) {
4929 var dataTransfer
= e
.originalEvent
.dataTransfer
;
4930 // Define drop effect
4931 dataTransfer
.dropEffect
= 'none';
4932 dataTransfer
.effectAllowed
= 'move';
4934 // We must set up a dataTransfer data property or Firefox seems to
4935 // ignore the fact the element is draggable.
4937 dataTransfer
.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
4939 // The above is only for Firefox. Move on if it fails.
4941 // Add dragging class
4942 this.$element
.addClass( 'oo-ui-draggableElement-dragging' );
4944 this.emit( 'dragstart', this );
4949 * Respond to dragend event.
4954 OO
.ui
.mixin
.DraggableElement
.prototype.onDragEnd = function () {
4955 this.$element
.removeClass( 'oo-ui-draggableElement-dragging' );
4956 this.emit( 'dragend' );
4960 * Handle drop event.
4963 * @param {jQuery.Event} event jQuery event
4966 OO
.ui
.mixin
.DraggableElement
.prototype.onDrop = function ( e
) {
4968 this.emit( 'drop', e
);
4972 * In order for drag/drop to work, the dragover event must
4973 * return false and stop propogation.
4977 OO
.ui
.mixin
.DraggableElement
.prototype.onDragOver = function ( e
) {
4983 * Store it in the DOM so we can access from the widget drag event
4986 * @param {number} Item index
4988 OO
.ui
.mixin
.DraggableElement
.prototype.setIndex = function ( index
) {
4989 if ( this.index
!== index
) {
4991 this.$element
.data( 'index', index
);
4999 * @return {number} Item index
5001 OO
.ui
.mixin
.DraggableElement
.prototype.getIndex = function () {
5006 * DraggableGroupElement is a mixin class used to create a group element to
5007 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
5008 * The class is used with OO.ui.mixin.DraggableElement.
5012 * @mixins OO.ui.mixin.GroupElement
5015 * @param {Object} [config] Configuration options
5016 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
5017 * should match the layout of the items. Items displayed in a single row
5018 * or in several rows should use horizontal orientation. The vertical orientation should only be
5019 * used when the items are displayed in a single column. Defaults to 'vertical'
5021 OO
.ui
.mixin
.DraggableGroupElement
= function OoUiMixinDraggableGroupElement( config
) {
5022 // Configuration initialization
5023 config
= config
|| {};
5025 // Parent constructor
5026 OO
.ui
.mixin
.GroupElement
.call( this, config
);
5029 this.orientation
= config
.orientation
|| 'vertical';
5030 this.dragItem
= null;
5031 this.itemDragOver
= null;
5033 this.sideInsertion
= '';
5037 dragstart
: 'itemDragStart',
5038 dragend
: 'itemDragEnd',
5041 this.connect( this, {
5042 itemDragStart
: 'onItemDragStart',
5043 itemDrop
: 'onItemDrop',
5044 itemDragEnd
: 'onItemDragEnd'
5047 dragover
: this.onDragOver
.bind( this ),
5048 dragleave
: this.onDragLeave
.bind( this )
5052 if ( Array
.isArray( config
.items
) ) {
5053 this.addItems( config
.items
);
5055 this.$placeholder
= $( '<div>' )
5056 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
5058 .addClass( 'oo-ui-draggableGroupElement' )
5059 .append( this.$status
)
5060 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation
=== 'horizontal' )
5061 .prepend( this.$placeholder
);
5065 OO
.mixinClass( OO
.ui
.mixin
.DraggableGroupElement
, OO
.ui
.mixin
.GroupElement
);
5070 * A 'reorder' event is emitted when the order of items in the group changes.
5073 * @param {OO.ui.mixin.DraggableElement} item Reordered item
5074 * @param {number} [newIndex] New index for the item
5080 * Respond to item drag start event
5083 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5085 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDragStart = function ( item
) {
5088 // Map the index of each object
5089 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5090 this.items
[ i
].setIndex( i
);
5093 if ( this.orientation
=== 'horizontal' ) {
5094 // Set the height of the indicator
5095 this.$placeholder
.css( {
5096 height
: item
.$element
.outerHeight(),
5100 // Set the width of the indicator
5101 this.$placeholder
.css( {
5103 width
: item
.$element
.outerWidth()
5106 this.setDragItem( item
);
5110 * Respond to item drag end event
5114 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDragEnd = function () {
5115 this.unsetDragItem();
5120 * Handle drop event and switch the order of the items accordingly
5123 * @param {OO.ui.mixin.DraggableElement} item Dropped item
5126 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDrop = function ( item
) {
5127 var toIndex
= item
.getIndex();
5128 // Check if the dropped item is from the current group
5129 // TODO: Figure out a way to configure a list of legally droppable
5130 // elements even if they are not yet in the list
5131 if ( this.getDragItem() ) {
5132 // If the insertion point is 'after', the insertion index
5133 // is shifted to the right (or to the left in RTL, hence 'after')
5134 if ( this.sideInsertion
=== 'after' ) {
5137 // Emit change event
5138 this.emit( 'reorder', this.getDragItem(), toIndex
);
5140 this.unsetDragItem();
5141 // Return false to prevent propogation
5146 * Handle dragleave event.
5150 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onDragLeave = function () {
5151 // This means the item was dragged outside the widget
5154 .addClass( 'oo-ui-element-hidden' );
5158 * Respond to dragover event
5161 * @param {jQuery.Event} event Event details
5163 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onDragOver = function ( e
) {
5164 var dragOverObj
, $optionWidget
, itemOffset
, itemMidpoint
, itemBoundingRect
,
5165 itemSize
, cssOutput
, dragPosition
, itemIndex
, itemPosition
,
5166 clientX
= e
.originalEvent
.clientX
,
5167 clientY
= e
.originalEvent
.clientY
;
5169 // Get the OptionWidget item we are dragging over
5170 dragOverObj
= this.getElementDocument().elementFromPoint( clientX
, clientY
);
5171 $optionWidget
= $( dragOverObj
).closest( '.oo-ui-draggableElement' );
5172 if ( $optionWidget
[ 0 ] ) {
5173 itemOffset
= $optionWidget
.offset();
5174 itemBoundingRect
= $optionWidget
[ 0 ].getBoundingClientRect();
5175 itemPosition
= $optionWidget
.position();
5176 itemIndex
= $optionWidget
.data( 'index' );
5181 this.isDragging() &&
5182 itemIndex
!== this.getDragItem().getIndex()
5184 if ( this.orientation
=== 'horizontal' ) {
5185 // Calculate where the mouse is relative to the item width
5186 itemSize
= itemBoundingRect
.width
;
5187 itemMidpoint
= itemBoundingRect
.left
+ itemSize
/ 2;
5188 dragPosition
= clientX
;
5189 // Which side of the item we hover over will dictate
5190 // where the placeholder will appear, on the left or
5193 left
: dragPosition
< itemMidpoint
? itemPosition
.left
: itemPosition
.left
+ itemSize
,
5194 top
: itemPosition
.top
5197 // Calculate where the mouse is relative to the item height
5198 itemSize
= itemBoundingRect
.height
;
5199 itemMidpoint
= itemBoundingRect
.top
+ itemSize
/ 2;
5200 dragPosition
= clientY
;
5201 // Which side of the item we hover over will dictate
5202 // where the placeholder will appear, on the top or
5205 top
: dragPosition
< itemMidpoint
? itemPosition
.top
: itemPosition
.top
+ itemSize
,
5206 left
: itemPosition
.left
5209 // Store whether we are before or after an item to rearrange
5210 // For horizontal layout, we need to account for RTL, as this is flipped
5211 if ( this.orientation
=== 'horizontal' && this.$element
.css( 'direction' ) === 'rtl' ) {
5212 this.sideInsertion
= dragPosition
< itemMidpoint
? 'after' : 'before';
5214 this.sideInsertion
= dragPosition
< itemMidpoint
? 'before' : 'after';
5216 // Add drop indicator between objects
5219 .removeClass( 'oo-ui-element-hidden' );
5221 // This means the item was dragged outside the widget
5224 .addClass( 'oo-ui-element-hidden' );
5231 * Set a dragged item
5233 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5235 OO
.ui
.mixin
.DraggableGroupElement
.prototype.setDragItem = function ( item
) {
5236 this.dragItem
= item
;
5240 * Unset the current dragged item
5242 OO
.ui
.mixin
.DraggableGroupElement
.prototype.unsetDragItem = function () {
5243 this.dragItem
= null;
5244 this.itemDragOver
= null;
5245 this.$placeholder
.addClass( 'oo-ui-element-hidden' );
5246 this.sideInsertion
= '';
5250 * Get the item that is currently being dragged.
5252 * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
5254 OO
.ui
.mixin
.DraggableGroupElement
.prototype.getDragItem = function () {
5255 return this.dragItem
;
5259 * Check if an item in the group is currently being dragged.
5261 * @return {Boolean} Item is being dragged
5263 OO
.ui
.mixin
.DraggableGroupElement
.prototype.isDragging = function () {
5264 return this.getDragItem() !== null;
5268 * IconElement is often mixed into other classes to generate an icon.
5269 * Icons are graphics, about the size of normal text. They are used to aid the user
5270 * in locating a control or to convey information in a space-efficient way. See the
5271 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
5272 * included in the library.
5274 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5280 * @param {Object} [config] Configuration options
5281 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
5282 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
5283 * the icon element be set to an existing icon instead of the one generated by this class, set a
5284 * value using a jQuery selection. For example:
5286 * // Use a <div> tag instead of a <span>
5288 * // Use an existing icon element instead of the one generated by the class
5289 * $icon: this.$element
5290 * // Use an icon element from a child widget
5291 * $icon: this.childwidget.$element
5292 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
5293 * symbolic names. A map is used for i18n purposes and contains a `default` icon
5294 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
5295 * by the user's language.
5297 * Example of an i18n map:
5299 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5300 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
5301 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5302 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
5303 * text. The icon title is displayed when users move the mouse over the icon.
5305 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
5306 // Configuration initialization
5307 config
= config
|| {};
5312 this.iconTitle
= null;
5315 this.setIcon( config
.icon
|| this.constructor.static.icon
);
5316 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
5317 this.setIconElement( config
.$icon
|| $( '<span>' ) );
5322 OO
.initClass( OO
.ui
.mixin
.IconElement
);
5324 /* Static Properties */
5327 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
5328 * for i18n purposes and contains a `default` icon name and additional names keyed by
5329 * language code. The `default` name is used when no icon is keyed by the user's language.
5331 * Example of an i18n map:
5333 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5335 * Note: the static property will be overridden if the #icon configuration is used.
5339 * @property {Object|string}
5341 OO
.ui
.mixin
.IconElement
.static.icon
= null;
5344 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5345 * function that returns title text, or `null` for no title.
5347 * The static property will be overridden if the #iconTitle configuration is used.
5351 * @property {string|Function|null}
5353 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
5358 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5359 * applies to the specified icon element instead of the one created by the class. If an icon
5360 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5361 * and mixin methods will no longer affect the element.
5363 * @param {jQuery} $icon Element to use as icon
5365 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
5368 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
5369 .removeAttr( 'title' );
5373 .addClass( 'oo-ui-iconElement-icon' )
5374 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
5375 if ( this.iconTitle
!== null ) {
5376 this.$icon
.attr( 'title', this.iconTitle
);
5379 this.updateThemeClasses();
5383 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5384 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5387 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5388 * by language code, or `null` to remove the icon.
5391 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
5392 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
5393 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
5395 if ( this.icon
!== icon
) {
5397 if ( this.icon
!== null ) {
5398 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
5400 if ( icon
!== null ) {
5401 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
5407 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
5408 this.updateThemeClasses();
5414 * Set the icon title. Use `null` to remove the title.
5416 * @param {string|Function|null} iconTitle A text string used as the icon title,
5417 * a function that returns title text, or `null` for no title.
5420 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
5421 iconTitle
= typeof iconTitle
=== 'function' ||
5422 ( typeof iconTitle
=== 'string' && iconTitle
.length
) ?
5423 OO
.ui
.resolveMsg( iconTitle
) : null;
5425 if ( this.iconTitle
!== iconTitle
) {
5426 this.iconTitle
= iconTitle
;
5428 if ( this.iconTitle
!== null ) {
5429 this.$icon
.attr( 'title', iconTitle
);
5431 this.$icon
.removeAttr( 'title' );
5440 * Get the symbolic name of the icon.
5442 * @return {string} Icon name
5444 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
5449 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5451 * @return {string} Icon title text
5453 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
5454 return this.iconTitle
;
5458 * IndicatorElement is often mixed into other classes to generate an indicator.
5459 * Indicators are small graphics that are generally used in two ways:
5461 * - To draw attention to the status of an item. For example, an indicator might be
5462 * used to show that an item in a list has errors that need to be resolved.
5463 * - To clarify the function of a control that acts in an exceptional way (a button
5464 * that opens a menu instead of performing an action directly, for example).
5466 * For a list of indicators included in the library, please see the
5467 * [OOjs UI documentation on MediaWiki] [1].
5469 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5475 * @param {Object} [config] Configuration options
5476 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5477 * configuration is omitted, the indicator element will use a generated `<span>`.
5478 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5479 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5481 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5482 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5483 * or a function that returns title text. The indicator title is displayed when users move
5484 * the mouse over the indicator.
5486 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
5487 // Configuration initialization
5488 config
= config
|| {};
5491 this.$indicator
= null;
5492 this.indicator
= null;
5493 this.indicatorTitle
= null;
5496 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
5497 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
5498 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
5503 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
5505 /* Static Properties */
5508 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5509 * The static property will be overridden if the #indicator configuration is used.
5513 * @property {string|null}
5515 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
5518 * A text string used as the indicator title, a function that returns title text, or `null`
5519 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5523 * @property {string|Function|null}
5525 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
5530 * Set the indicator element.
5532 * If an element is already set, it will be cleaned up before setting up the new element.
5534 * @param {jQuery} $indicator Element to use as indicator
5536 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
5537 if ( this.$indicator
) {
5539 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
5540 .removeAttr( 'title' );
5543 this.$indicator
= $indicator
5544 .addClass( 'oo-ui-indicatorElement-indicator' )
5545 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
5546 if ( this.indicatorTitle
!== null ) {
5547 this.$indicator
.attr( 'title', this.indicatorTitle
);
5550 this.updateThemeClasses();
5554 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5556 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5559 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
5560 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
5562 if ( this.indicator
!== indicator
) {
5563 if ( this.$indicator
) {
5564 if ( this.indicator
!== null ) {
5565 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
5567 if ( indicator
!== null ) {
5568 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
5571 this.indicator
= indicator
;
5574 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
5575 this.updateThemeClasses();
5581 * Set the indicator title.
5583 * The title is displayed when a user moves the mouse over the indicator.
5585 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5586 * `null` for no indicator title
5589 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
5590 indicatorTitle
= typeof indicatorTitle
=== 'function' ||
5591 ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ?
5592 OO
.ui
.resolveMsg( indicatorTitle
) : null;
5594 if ( this.indicatorTitle
!== indicatorTitle
) {
5595 this.indicatorTitle
= indicatorTitle
;
5596 if ( this.$indicator
) {
5597 if ( this.indicatorTitle
!== null ) {
5598 this.$indicator
.attr( 'title', indicatorTitle
);
5600 this.$indicator
.removeAttr( 'title' );
5609 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5611 * @return {string} Symbolic name of indicator
5613 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
5614 return this.indicator
;
5618 * Get the indicator title.
5620 * The title is displayed when a user moves the mouse over the indicator.
5622 * @return {string} Indicator title text
5624 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
5625 return this.indicatorTitle
;
5629 * LabelElement is often mixed into other classes to generate a label, which
5630 * helps identify the function of an interface element.
5631 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5633 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5639 * @param {Object} [config] Configuration options
5640 * @cfg {jQuery} [$label] The label element created by the class. If this
5641 * configuration is omitted, the label element will use a generated `<span>`.
5642 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
5643 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
5644 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
5645 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5646 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5647 * The label will be truncated to fit if necessary.
5649 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
5650 // Configuration initialization
5651 config
= config
|| {};
5656 this.autoFitLabel
= config
.autoFitLabel
=== undefined || !!config
.autoFitLabel
;
5659 this.setLabel( config
.label
|| this.constructor.static.label
);
5660 this.setLabelElement( config
.$label
|| $( '<span>' ) );
5665 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
5670 * @event labelChange
5671 * @param {string} value
5674 /* Static Properties */
5677 * The label text. The label can be specified as a plaintext string, a function that will
5678 * produce a string in the future, or `null` for no label. The static value will
5679 * be overridden if a label is specified with the #label config option.
5683 * @property {string|Function|null}
5685 OO
.ui
.mixin
.LabelElement
.static.label
= null;
5690 * Set the label element.
5692 * If an element is already set, it will be cleaned up before setting up the new element.
5694 * @param {jQuery} $label Element to use as label
5696 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
5697 if ( this.$label
) {
5698 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
5701 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
5702 this.setLabelContent( this.label
);
5708 * An empty string will result in the label being hidden. A string containing only whitespace will
5709 * be converted to a single ` `.
5711 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5712 * text; or null for no label
5715 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
5716 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
5717 label
= ( ( typeof label
=== 'string' && label
.length
) || label
instanceof jQuery
|| label
instanceof OO
.ui
.HtmlSnippet
) ? label
: null;
5719 this.$element
.toggleClass( 'oo-ui-labelElement', !!label
);
5721 if ( this.label
!== label
) {
5722 if ( this.$label
) {
5723 this.setLabelContent( label
);
5726 this.emit( 'labelChange' );
5735 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5736 * text; or null for no label
5738 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
5747 OO
.ui
.mixin
.LabelElement
.prototype.fitLabel = function () {
5748 if ( this.$label
&& this.$label
.autoEllipsis
&& this.autoFitLabel
) {
5749 this.$label
.autoEllipsis( { hasSpan
: false, tooltip
: true } );
5756 * Set the content of the label.
5758 * Do not call this method until after the label element has been set by #setLabelElement.
5761 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5762 * text; or null for no label
5764 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
5765 if ( typeof label
=== 'string' ) {
5766 if ( label
.match( /^\s*$/ ) ) {
5767 // Convert whitespace only string to a single non-breaking space
5768 this.$label
.html( ' ' );
5770 this.$label
.text( label
);
5772 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
5773 this.$label
.html( label
.toString() );
5774 } else if ( label
instanceof jQuery
) {
5775 this.$label
.empty().append( label
);
5777 this.$label
.empty();
5782 * LookupElement is a mixin that creates a {@link OO.ui.FloatingMenuSelectWidget menu} of suggested values for
5783 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
5784 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
5785 * from the lookup menu, that value becomes the value of the input field.
5787 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
5788 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
5789 * re-enable lookups.
5791 * See the [OOjs UI demos][1] for an example.
5793 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
5799 * @param {Object} [config] Configuration options
5800 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
5801 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
5802 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
5803 * By default, the lookup menu is not generated and displayed until the user begins to type.
5805 OO
.ui
.mixin
.LookupElement
= function OoUiMixinLookupElement( config
) {
5806 // Configuration initialization
5807 config
= config
|| {};
5810 this.$overlay
= config
.$overlay
|| this.$element
;
5811 this.lookupMenu
= new OO
.ui
.FloatingMenuSelectWidget( {
5814 $container
: config
.$container
|| this.$element
5817 this.allowSuggestionsWhenEmpty
= config
.allowSuggestionsWhenEmpty
|| false;
5819 this.lookupCache
= {};
5820 this.lookupQuery
= null;
5821 this.lookupRequest
= null;
5822 this.lookupsDisabled
= false;
5823 this.lookupInputFocused
= false;
5827 focus
: this.onLookupInputFocus
.bind( this ),
5828 blur
: this.onLookupInputBlur
.bind( this ),
5829 mousedown
: this.onLookupInputMouseDown
.bind( this )
5831 this.connect( this, { change
: 'onLookupInputChange' } );
5832 this.lookupMenu
.connect( this, {
5833 toggle
: 'onLookupMenuToggle',
5834 choose
: 'onLookupMenuItemChoose'
5838 this.$element
.addClass( 'oo-ui-lookupElement' );
5839 this.lookupMenu
.$element
.addClass( 'oo-ui-lookupElement-menu' );
5840 this.$overlay
.append( this.lookupMenu
.$element
);
5846 * Handle input focus event.
5849 * @param {jQuery.Event} e Input focus event
5851 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputFocus = function () {
5852 this.lookupInputFocused
= true;
5853 this.populateLookupMenu();
5857 * Handle input blur event.
5860 * @param {jQuery.Event} e Input blur event
5862 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputBlur = function () {
5863 this.closeLookupMenu();
5864 this.lookupInputFocused
= false;
5868 * Handle input mouse down event.
5871 * @param {jQuery.Event} e Input mouse down event
5873 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputMouseDown = function () {
5874 // Only open the menu if the input was already focused.
5875 // This way we allow the user to open the menu again after closing it with Esc
5876 // by clicking in the input. Opening (and populating) the menu when initially
5877 // clicking into the input is handled by the focus handler.
5878 if ( this.lookupInputFocused
&& !this.lookupMenu
.isVisible() ) {
5879 this.populateLookupMenu();
5884 * Handle input change event.
5887 * @param {string} value New input value
5889 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputChange = function () {
5890 if ( this.lookupInputFocused
) {
5891 this.populateLookupMenu();
5896 * Handle the lookup menu being shown/hidden.
5899 * @param {boolean} visible Whether the lookup menu is now visible.
5901 OO
.ui
.mixin
.LookupElement
.prototype.onLookupMenuToggle = function ( visible
) {
5903 // When the menu is hidden, abort any active request and clear the menu.
5904 // This has to be done here in addition to closeLookupMenu(), because
5905 // MenuSelectWidget will close itself when the user presses Esc.
5906 this.abortLookupRequest();
5907 this.lookupMenu
.clearItems();
5912 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5915 * @param {OO.ui.MenuOptionWidget} item Selected item
5917 OO
.ui
.mixin
.LookupElement
.prototype.onLookupMenuItemChoose = function ( item
) {
5918 this.setValue( item
.getData() );
5925 * @return {OO.ui.FloatingMenuSelectWidget}
5927 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenu = function () {
5928 return this.lookupMenu
;
5932 * Disable or re-enable lookups.
5934 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
5936 * @param {boolean} disabled Disable lookups
5938 OO
.ui
.mixin
.LookupElement
.prototype.setLookupsDisabled = function ( disabled
) {
5939 this.lookupsDisabled
= !!disabled
;
5943 * Open the menu. If there are no entries in the menu, this does nothing.
5948 OO
.ui
.mixin
.LookupElement
.prototype.openLookupMenu = function () {
5949 if ( !this.lookupMenu
.isEmpty() ) {
5950 this.lookupMenu
.toggle( true );
5956 * Close the menu, empty it, and abort any pending request.
5961 OO
.ui
.mixin
.LookupElement
.prototype.closeLookupMenu = function () {
5962 this.lookupMenu
.toggle( false );
5963 this.abortLookupRequest();
5964 this.lookupMenu
.clearItems();
5969 * Request menu items based on the input's current value, and when they arrive,
5970 * populate the menu with these items and show the menu.
5972 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
5977 OO
.ui
.mixin
.LookupElement
.prototype.populateLookupMenu = function () {
5979 value
= this.getValue();
5981 if ( this.lookupsDisabled
|| this.isReadOnly() ) {
5985 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
5986 if ( !this.allowSuggestionsWhenEmpty
&& value
=== '' ) {
5987 this.closeLookupMenu();
5988 // Skip population if there is already a request pending for the current value
5989 } else if ( value
!== this.lookupQuery
) {
5990 this.getLookupMenuItems()
5991 .done( function ( items
) {
5992 widget
.lookupMenu
.clearItems();
5993 if ( items
.length
) {
5997 widget
.initializeLookupMenuSelection();
5999 widget
.lookupMenu
.toggle( false );
6002 .fail( function () {
6003 widget
.lookupMenu
.clearItems();
6011 * Highlight the first selectable item in the menu.
6016 OO
.ui
.mixin
.LookupElement
.prototype.initializeLookupMenuSelection = function () {
6017 if ( !this.lookupMenu
.getSelectedItem() ) {
6018 this.lookupMenu
.highlightItem( this.lookupMenu
.getFirstSelectableItem() );
6023 * Get lookup menu items for the current query.
6026 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
6027 * the done event. If the request was aborted to make way for a subsequent request, this promise
6028 * will not be rejected: it will remain pending forever.
6030 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenuItems = function () {
6032 value
= this.getValue(),
6033 deferred
= $.Deferred(),
6036 this.abortLookupRequest();
6037 if ( Object
.prototype.hasOwnProperty
.call( this.lookupCache
, value
) ) {
6038 deferred
.resolve( this.getLookupMenuOptionsFromData( this.lookupCache
[ value
] ) );
6041 this.lookupQuery
= value
;
6042 ourRequest
= this.lookupRequest
= this.getLookupRequest();
6044 .always( function () {
6045 // We need to pop pending even if this is an old request, otherwise
6046 // the widget will remain pending forever.
6047 // TODO: this assumes that an aborted request will fail or succeed soon after
6048 // being aborted, or at least eventually. It would be nice if we could popPending()
6049 // at abort time, but only if we knew that we hadn't already called popPending()
6050 // for that request.
6051 widget
.popPending();
6053 .done( function ( response
) {
6054 // If this is an old request (and aborting it somehow caused it to still succeed),
6055 // ignore its success completely
6056 if ( ourRequest
=== widget
.lookupRequest
) {
6057 widget
.lookupQuery
= null;
6058 widget
.lookupRequest
= null;
6059 widget
.lookupCache
[ value
] = widget
.getLookupCacheDataFromResponse( response
);
6060 deferred
.resolve( widget
.getLookupMenuOptionsFromData( widget
.lookupCache
[ value
] ) );
6063 .fail( function () {
6064 // If this is an old request (or a request failing because it's being aborted),
6065 // ignore its failure completely
6066 if ( ourRequest
=== widget
.lookupRequest
) {
6067 widget
.lookupQuery
= null;
6068 widget
.lookupRequest
= null;
6073 return deferred
.promise();
6077 * Abort the currently pending lookup request, if any.
6081 OO
.ui
.mixin
.LookupElement
.prototype.abortLookupRequest = function () {
6082 var oldRequest
= this.lookupRequest
;
6084 // First unset this.lookupRequest to the fail handler will notice
6085 // that the request is no longer current
6086 this.lookupRequest
= null;
6087 this.lookupQuery
= null;
6093 * Get a new request object of the current lookup query value.
6097 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
6099 OO
.ui
.mixin
.LookupElement
.prototype.getLookupRequest = function () {
6100 // Stub, implemented in subclass
6105 * Pre-process data returned by the request from #getLookupRequest.
6107 * The return value of this function will be cached, and any further queries for the given value
6108 * will use the cache rather than doing API requests.
6112 * @param {Mixed} response Response from server
6113 * @return {Mixed} Cached result data
6115 OO
.ui
.mixin
.LookupElement
.prototype.getLookupCacheDataFromResponse = function () {
6116 // Stub, implemented in subclass
6121 * Get a list of menu option widgets from the (possibly cached) data returned by
6122 * #getLookupCacheDataFromResponse.
6126 * @param {Mixed} data Cached result data, usually an array
6127 * @return {OO.ui.MenuOptionWidget[]} Menu items
6129 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenuOptionsFromData = function () {
6130 // Stub, implemented in subclass
6135 * Set the read-only state of the widget.
6137 * This will also disable/enable the lookups functionality.
6139 * @param {boolean} readOnly Make input read-only
6142 OO
.ui
.mixin
.LookupElement
.prototype.setReadOnly = function ( readOnly
) {
6144 // Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget
6145 OO
.ui
.TextInputWidget
.prototype.setReadOnly
.call( this, readOnly
);
6147 // During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor
6148 if ( this.isReadOnly() && this.lookupMenu
) {
6149 this.closeLookupMenu();
6156 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
6157 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
6158 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
6159 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
6165 * @param {Object} [config] Configuration options
6166 * @cfg {Object} [popup] Configuration to pass to popup
6167 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
6169 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
6170 // Configuration initialization
6171 config
= config
|| {};
6174 this.popup
= new OO
.ui
.PopupWidget( $.extend(
6175 { autoClose
: true },
6177 { $autoCloseIgnore
: this.$element
}
6186 * @return {OO.ui.PopupWidget} Popup widget
6188 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
6193 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
6194 * additional functionality to an element created by another class. The class provides
6195 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
6196 * which are used to customize the look and feel of a widget to better describe its
6197 * importance and functionality.
6199 * The library currently contains the following styling flags for general use:
6201 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
6202 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
6203 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
6205 * The flags affect the appearance of the buttons:
6208 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
6209 * var button1 = new OO.ui.ButtonWidget( {
6210 * label: 'Constructive',
6211 * flags: 'constructive'
6213 * var button2 = new OO.ui.ButtonWidget( {
6214 * label: 'Destructive',
6215 * flags: 'destructive'
6217 * var button3 = new OO.ui.ButtonWidget( {
6218 * label: 'Progressive',
6219 * flags: 'progressive'
6221 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
6223 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
6224 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6226 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6232 * @param {Object} [config] Configuration options
6233 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
6234 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
6235 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6236 * @cfg {jQuery} [$flagged] The flagged element. By default,
6237 * the flagged functionality is applied to the element created by the class ($element).
6238 * If a different element is specified, the flagged functionality will be applied to it instead.
6240 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
6241 // Configuration initialization
6242 config
= config
|| {};
6246 this.$flagged
= null;
6249 this.setFlags( config
.flags
);
6250 this.setFlaggedElement( config
.$flagged
|| this.$element
);
6257 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
6258 * parameter contains the name of each modified flag and indicates whether it was
6261 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
6262 * that the flag was added, `false` that the flag was removed.
6268 * Set the flagged element.
6270 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
6271 * If an element is already set, the method will remove the mixin’s effect on that element.
6273 * @param {jQuery} $flagged Element that should be flagged
6275 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
6276 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
6277 return 'oo-ui-flaggedElement-' + flag
;
6280 if ( this.$flagged
) {
6281 this.$flagged
.removeClass( classNames
);
6284 this.$flagged
= $flagged
.addClass( classNames
);
6288 * Check if the specified flag is set.
6290 * @param {string} flag Name of flag
6291 * @return {boolean} The flag is set
6293 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
6294 // This may be called before the constructor, thus before this.flags is set
6295 return this.flags
&& ( flag
in this.flags
);
6299 * Get the names of all flags set.
6301 * @return {string[]} Flag names
6303 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
6304 // This may be called before the constructor, thus before this.flags is set
6305 return Object
.keys( this.flags
|| {} );
6314 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
6315 var flag
, className
,
6318 classPrefix
= 'oo-ui-flaggedElement-';
6320 for ( flag
in this.flags
) {
6321 className
= classPrefix
+ flag
;
6322 changes
[ flag
] = false;
6323 delete this.flags
[ flag
];
6324 remove
.push( className
);
6327 if ( this.$flagged
) {
6328 this.$flagged
.removeClass( remove
.join( ' ' ) );
6331 this.updateThemeClasses();
6332 this.emit( 'flag', changes
);
6338 * Add one or more flags.
6340 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
6341 * or an object keyed by flag name with a boolean value that indicates whether the flag should
6342 * be added (`true`) or removed (`false`).
6346 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
6347 var i
, len
, flag
, className
,
6351 classPrefix
= 'oo-ui-flaggedElement-';
6353 if ( typeof flags
=== 'string' ) {
6354 className
= classPrefix
+ flags
;
6356 if ( !this.flags
[ flags
] ) {
6357 this.flags
[ flags
] = true;
6358 add
.push( className
);
6360 } else if ( Array
.isArray( flags
) ) {
6361 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
6363 className
= classPrefix
+ flag
;
6365 if ( !this.flags
[ flag
] ) {
6366 changes
[ flag
] = true;
6367 this.flags
[ flag
] = true;
6368 add
.push( className
);
6371 } else if ( OO
.isPlainObject( flags
) ) {
6372 for ( flag
in flags
) {
6373 className
= classPrefix
+ flag
;
6374 if ( flags
[ flag
] ) {
6376 if ( !this.flags
[ flag
] ) {
6377 changes
[ flag
] = true;
6378 this.flags
[ flag
] = true;
6379 add
.push( className
);
6383 if ( this.flags
[ flag
] ) {
6384 changes
[ flag
] = false;
6385 delete this.flags
[ flag
];
6386 remove
.push( className
);
6392 if ( this.$flagged
) {
6394 .addClass( add
.join( ' ' ) )
6395 .removeClass( remove
.join( ' ' ) );
6398 this.updateThemeClasses();
6399 this.emit( 'flag', changes
);
6405 * TitledElement is mixed into other classes to provide a `title` attribute.
6406 * Titles are rendered by the browser and are made visible when the user moves
6407 * the mouse over the element. Titles are not visible on touch devices.
6410 * // TitledElement provides a 'title' attribute to the
6411 * // ButtonWidget class
6412 * var button = new OO.ui.ButtonWidget( {
6413 * label: 'Button with Title',
6414 * title: 'I am a button'
6416 * $( 'body' ).append( button.$element );
6422 * @param {Object} [config] Configuration options
6423 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6424 * If this config is omitted, the title functionality is applied to $element, the
6425 * element created by the class.
6426 * @cfg {string|Function} [title] The title text or a function that returns text. If
6427 * this config is omitted, the value of the {@link #static-title static title} property is used.
6429 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
6430 // Configuration initialization
6431 config
= config
|| {};
6434 this.$titled
= null;
6438 this.setTitle( config
.title
|| this.constructor.static.title
);
6439 this.setTitledElement( config
.$titled
|| this.$element
);
6444 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
6446 /* Static Properties */
6449 * The title text, a function that returns text, or `null` for no title. The value of the static property
6450 * is overridden if the #title config option is used.
6454 * @property {string|Function|null}
6456 OO
.ui
.mixin
.TitledElement
.static.title
= null;
6461 * Set the titled element.
6463 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6464 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6466 * @param {jQuery} $titled Element that should use the 'titled' functionality
6468 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
6469 if ( this.$titled
) {
6470 this.$titled
.removeAttr( 'title' );
6473 this.$titled
= $titled
;
6475 this.$titled
.attr( 'title', this.title
);
6482 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6485 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
6486 title
= typeof title
=== 'string' ? OO
.ui
.resolveMsg( title
) : null;
6488 if ( this.title
!== title
) {
6489 if ( this.$titled
) {
6490 if ( title
!== null ) {
6491 this.$titled
.attr( 'title', title
);
6493 this.$titled
.removeAttr( 'title' );
6505 * @return {string} Title string
6507 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
6512 * Element that can be automatically clipped to visible boundaries.
6514 * Whenever the element's natural height changes, you have to call
6515 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
6516 * clipping correctly.
6518 * The dimensions of #$clippableContainer will be compared to the boundaries of the
6519 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
6520 * then #$clippable will be given a fixed reduced height and/or width and will be made
6521 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
6522 * but you can build a static footer by setting #$clippableContainer to an element that contains
6523 * #$clippable and the footer.
6529 * @param {Object} [config] Configuration options
6530 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
6531 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
6532 * omit to use #$clippable
6534 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
6535 // Configuration initialization
6536 config
= config
|| {};
6539 this.$clippable
= null;
6540 this.$clippableContainer
= null;
6541 this.clipping
= false;
6542 this.clippedHorizontally
= false;
6543 this.clippedVertically
= false;
6544 this.$clippableScrollableContainer
= null;
6545 this.$clippableScroller
= null;
6546 this.$clippableWindow
= null;
6547 this.idealWidth
= null;
6548 this.idealHeight
= null;
6549 this.onClippableScrollHandler
= this.clip
.bind( this );
6550 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
6553 if ( config
.$clippableContainer
) {
6554 this.setClippableContainer( config
.$clippableContainer
);
6556 this.setClippableElement( config
.$clippable
|| this.$element
);
6562 * Set clippable element.
6564 * If an element is already set, it will be cleaned up before setting up the new element.
6566 * @param {jQuery} $clippable Element to make clippable
6568 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
6569 if ( this.$clippable
) {
6570 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
6571 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6572 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6575 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
6580 * Set clippable container.
6582 * This is the container that will be measured when deciding whether to clip. When clipping,
6583 * #$clippable will be resized in order to keep the clippable container fully visible.
6585 * If the clippable container is unset, #$clippable will be used.
6587 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
6589 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableContainer = function ( $clippableContainer
) {
6590 this.$clippableContainer
= $clippableContainer
;
6591 if ( this.$clippable
) {
6599 * Do not turn clipping on until after the element is attached to the DOM and visible.
6601 * @param {boolean} [clipping] Enable clipping, omit to toggle
6604 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
6605 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
6607 if ( this.clipping
!== clipping
) {
6608 this.clipping
= clipping
;
6610 this.$clippableScrollableContainer
= $( this.getClosestScrollableElementContainer() );
6611 // If the clippable container is the root, we have to listen to scroll events and check
6612 // jQuery.scrollTop on the window because of browser inconsistencies
6613 this.$clippableScroller
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
6614 $( OO
.ui
.Element
.static.getWindow( this.$clippableScrollableContainer
) ) :
6615 this.$clippableScrollableContainer
;
6616 this.$clippableScroller
.on( 'scroll', this.onClippableScrollHandler
);
6617 this.$clippableWindow
= $( this.getElementWindow() )
6618 .on( 'resize', this.onClippableWindowResizeHandler
);
6619 // Initial clip after visible
6622 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6623 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6625 this.$clippableScrollableContainer
= null;
6626 this.$clippableScroller
.off( 'scroll', this.onClippableScrollHandler
);
6627 this.$clippableScroller
= null;
6628 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
6629 this.$clippableWindow
= null;
6637 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6639 * @return {boolean} Element will be clipped to the visible area
6641 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
6642 return this.clipping
;
6646 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6648 * @return {boolean} Part of the element is being clipped
6650 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
6651 return this.clippedHorizontally
|| this.clippedVertically
;
6655 * Check if the right of the element is being clipped by the nearest scrollable container.
6657 * @return {boolean} Part of the element is being clipped
6659 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
6660 return this.clippedHorizontally
;
6664 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6666 * @return {boolean} Part of the element is being clipped
6668 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
6669 return this.clippedVertically
;
6673 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6675 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6676 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6678 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
6679 this.idealWidth
= width
;
6680 this.idealHeight
= height
;
6682 if ( !this.clipping
) {
6683 // Update dimensions
6684 this.$clippable
.css( { width
: width
, height
: height
} );
6686 // While clipping, idealWidth and idealHeight are not considered
6690 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6691 * the element's natural height changes.
6693 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6694 * overlapped by, the visible area of the nearest scrollable container.
6698 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
6699 var $container
, extraHeight
, extraWidth
, ccOffset
,
6700 $scrollableContainer
, scOffset
, scHeight
, scWidth
,
6701 ccWidth
, scrollerIsWindow
, scrollTop
, scrollLeft
,
6702 desiredWidth
, desiredHeight
, allotedWidth
, allotedHeight
,
6703 naturalWidth
, naturalHeight
, clipWidth
, clipHeight
,
6704 buffer
= 7; // Chosen by fair dice roll
6706 if ( !this.clipping
) {
6707 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
6711 $container
= this.$clippableContainer
|| this.$clippable
;
6712 extraHeight
= $container
.outerHeight() - this.$clippable
.outerHeight();
6713 extraWidth
= $container
.outerWidth() - this.$clippable
.outerWidth();
6714 ccOffset
= $container
.offset();
6715 $scrollableContainer
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
6716 this.$clippableWindow
: this.$clippableScrollableContainer
;
6717 scOffset
= $scrollableContainer
.offset() || { top
: 0, left
: 0 };
6718 scHeight
= $scrollableContainer
.innerHeight() - buffer
;
6719 scWidth
= $scrollableContainer
.innerWidth() - buffer
;
6720 ccWidth
= $container
.outerWidth() + buffer
;
6721 scrollerIsWindow
= this.$clippableScroller
[ 0 ] === this.$clippableWindow
[ 0 ];
6722 scrollTop
= scrollerIsWindow
? this.$clippableScroller
.scrollTop() : 0;
6723 scrollLeft
= scrollerIsWindow
? this.$clippableScroller
.scrollLeft() : 0;
6724 desiredWidth
= ccOffset
.left
< 0 ?
6725 ccWidth
+ ccOffset
.left
:
6726 ( scOffset
.left
+ scrollLeft
+ scWidth
) - ccOffset
.left
;
6727 desiredHeight
= ( scOffset
.top
+ scrollTop
+ scHeight
) - ccOffset
.top
;
6728 allotedWidth
= desiredWidth
- extraWidth
;
6729 allotedHeight
= desiredHeight
- extraHeight
;
6730 naturalWidth
= this.$clippable
.prop( 'scrollWidth' );
6731 naturalHeight
= this.$clippable
.prop( 'scrollHeight' );
6732 clipWidth
= allotedWidth
< naturalWidth
;
6733 clipHeight
= allotedHeight
< naturalHeight
;
6736 this.$clippable
.css( { overflowX
: 'scroll', width
: Math
.max( 0, allotedWidth
) } );
6738 this.$clippable
.css( { width
: this.idealWidth
? this.idealWidth
- extraWidth
: '', overflowX
: '' } );
6741 this.$clippable
.css( { overflowY
: 'scroll', height
: Math
.max( 0, allotedHeight
) } );
6743 this.$clippable
.css( { height
: this.idealHeight
? this.idealHeight
- extraHeight
: '', overflowY
: '' } );
6746 // If we stopped clipping in at least one of the dimensions
6747 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
6748 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6751 this.clippedHorizontally
= clipWidth
;
6752 this.clippedVertically
= clipHeight
;
6758 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
6759 * Accesskeys allow an user to go to a specific element by using
6760 * a shortcut combination of a browser specific keys + the key
6764 * // AccessKeyedElement provides an 'accesskey' attribute to the
6765 * // ButtonWidget class
6766 * var button = new OO.ui.ButtonWidget( {
6767 * label: 'Button with Accesskey',
6770 * $( 'body' ).append( button.$element );
6776 * @param {Object} [config] Configuration options
6777 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
6778 * If this config is omitted, the accesskey functionality is applied to $element, the
6779 * element created by the class.
6780 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
6781 * this config is omitted, no accesskey will be added.
6783 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
6784 // Configuration initialization
6785 config
= config
|| {};
6788 this.$accessKeyed
= null;
6789 this.accessKey
= null;
6792 this.setAccessKey( config
.accessKey
|| null );
6793 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
6798 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
6800 /* Static Properties */
6803 * The access key, a function that returns a key, or `null` for no accesskey.
6807 * @property {string|Function|null}
6809 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
6814 * Set the accesskeyed element.
6816 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
6817 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
6819 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
6821 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
6822 if ( this.$accessKeyed
) {
6823 this.$accessKeyed
.removeAttr( 'accesskey' );
6826 this.$accessKeyed
= $accessKeyed
;
6827 if ( this.accessKey
) {
6828 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
6835 * @param {string|Function|null} accesskey Key, a function that returns a key, or `null` for no accesskey
6838 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
6839 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
6841 if ( this.accessKey
!== accessKey
) {
6842 if ( this.$accessKeyed
) {
6843 if ( accessKey
!== null ) {
6844 this.$accessKeyed
.attr( 'accesskey', accessKey
);
6846 this.$accessKeyed
.removeAttr( 'accesskey' );
6849 this.accessKey
= accessKey
;
6858 * @return {string} accessKey string
6860 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
6861 return this.accessKey
;
6865 * Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute {@link OO.ui.Toolbar toolbars}.
6866 * Each tool is configured with a static name, title, and icon and is customized with the command to carry
6867 * out when the tool is selected. Tools must also be registered with a {@link OO.ui.ToolFactory tool factory},
6868 * which creates the tools on demand.
6870 * Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup},
6871 * {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which determine how
6872 * the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an example.
6874 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
6875 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
6879 * @extends OO.ui.Widget
6880 * @mixins OO.ui.mixin.IconElement
6881 * @mixins OO.ui.mixin.FlaggedElement
6882 * @mixins OO.ui.mixin.TabIndexedElement
6885 * @param {OO.ui.ToolGroup} toolGroup
6886 * @param {Object} [config] Configuration options
6887 * @cfg {string|Function} [title] Title text or a function that returns text. If this config is omitted, the value of
6888 * the {@link #static-title static title} property is used.
6890 * The title is used in different ways depending on the type of toolgroup that contains the tool. The
6891 * 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
6892 * part of a {@link OO.ui.ListToolGroup list} or {@link OO.ui.MenuToolGroup menu} toolgroup.
6894 * For bar toolgroups, a description of the accelerator key is appended to the title if an accelerator key
6895 * is associated with an action by the same name as the tool and accelerator functionality has been added to the application.
6896 * To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method.
6898 OO
.ui
.Tool
= function OoUiTool( toolGroup
, config
) {
6899 // Allow passing positional parameters inside the config object
6900 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
6902 toolGroup
= config
.toolGroup
;
6905 // Configuration initialization
6906 config
= config
|| {};
6908 // Parent constructor
6909 OO
.ui
.Tool
.parent
.call( this, config
);
6912 this.toolGroup
= toolGroup
;
6913 this.toolbar
= this.toolGroup
.getToolbar();
6914 this.active
= false;
6915 this.$title
= $( '<span>' );
6916 this.$accel
= $( '<span>' );
6917 this.$link
= $( '<a>' );
6920 // Mixin constructors
6921 OO
.ui
.mixin
.IconElement
.call( this, config
);
6922 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
6923 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$link
} ) );
6926 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
6929 this.$title
.addClass( 'oo-ui-tool-title' );
6931 .addClass( 'oo-ui-tool-accel' )
6933 // This may need to be changed if the key names are ever localized,
6934 // but for now they are essentially written in English
6939 .addClass( 'oo-ui-tool-link' )
6940 .append( this.$icon
, this.$title
, this.$accel
)
6941 .attr( 'role', 'button' );
6943 .data( 'oo-ui-tool', this )
6945 'oo-ui-tool ' + 'oo-ui-tool-name-' +
6946 this.constructor.static.name
.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
6948 .toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel
)
6949 .append( this.$link
);
6950 this.setTitle( config
.title
|| this.constructor.static.title
);
6955 OO
.inheritClass( OO
.ui
.Tool
, OO
.ui
.Widget
);
6956 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.IconElement
);
6957 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.FlaggedElement
);
6958 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.TabIndexedElement
);
6960 /* Static Properties */
6966 OO
.ui
.Tool
.static.tagName
= 'span';
6969 * Symbolic name of tool.
6971 * The symbolic name is used internally to register the tool with a {@link OO.ui.ToolFactory ToolFactory}. It can
6972 * also be used when adding tools to toolgroups.
6977 * @property {string}
6979 OO
.ui
.Tool
.static.name
= '';
6982 * Symbolic name of the group.
6984 * The group name is used to associate tools with each other so that they can be selected later by
6985 * a {@link OO.ui.ToolGroup toolgroup}.
6990 * @property {string}
6992 OO
.ui
.Tool
.static.group
= '';
6995 * 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.
7000 * @property {string|Function}
7002 OO
.ui
.Tool
.static.title
= '';
7005 * Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup.
7006 * Normally only the icon is displayed, or only the label if no icon is given.
7010 * @property {boolean}
7012 OO
.ui
.Tool
.static.displayBothIconAndLabel
= false;
7015 * Add tool to catch-all groups automatically.
7017 * A catch-all group, which contains all tools that do not currently belong to a toolgroup,
7018 * can be included in a toolgroup using the wildcard selector, an asterisk (*).
7022 * @property {boolean}
7024 OO
.ui
.Tool
.static.autoAddToCatchall
= true;
7027 * Add tool to named groups automatically.
7029 * By default, tools that are configured with a static ‘group’ property are added
7030 * to that group and will be selected when the symbolic name of the group is specified (e.g., when
7031 * toolgroups include tools by group name).
7034 * @property {boolean}
7037 OO
.ui
.Tool
.static.autoAddToGroup
= true;
7040 * Check if this tool is compatible with given data.
7042 * This is a stub that can be overriden to provide support for filtering tools based on an
7043 * arbitrary piece of information (e.g., where the cursor is in a document). The implementation
7044 * must also call this method so that the compatibility check can be performed.
7048 * @param {Mixed} data Data to check
7049 * @return {boolean} Tool can be used with data
7051 OO
.ui
.Tool
.static.isCompatibleWith = function () {
7058 * Handle the toolbar state being updated.
7060 * This is an abstract method that must be overridden in a concrete subclass.
7065 OO
.ui
.Tool
.prototype.onUpdateState = function () {
7067 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
7072 * Handle the tool being selected.
7074 * This is an abstract method that must be overridden in a concrete subclass.
7079 OO
.ui
.Tool
.prototype.onSelect = function () {
7081 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
7086 * Check if the tool is active.
7088 * Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed
7089 * with the #setActive method. Additional CSS is applied to the tool to reflect the active state.
7091 * @return {boolean} Tool is active
7093 OO
.ui
.Tool
.prototype.isActive = function () {
7098 * Make the tool appear active or inactive.
7100 * This method should be called within #onSelect or #onUpdateState event handlers to make the tool
7101 * appear pressed or not.
7103 * @param {boolean} state Make tool appear active
7105 OO
.ui
.Tool
.prototype.setActive = function ( state
) {
7106 this.active
= !!state
;
7107 if ( this.active
) {
7108 this.$element
.addClass( 'oo-ui-tool-active' );
7110 this.$element
.removeClass( 'oo-ui-tool-active' );
7115 * Set the tool #title.
7117 * @param {string|Function} title Title text or a function that returns text
7120 OO
.ui
.Tool
.prototype.setTitle = function ( title
) {
7121 this.title
= OO
.ui
.resolveMsg( title
);
7127 * Get the tool #title.
7129 * @return {string} Title text
7131 OO
.ui
.Tool
.prototype.getTitle = function () {
7136 * Get the tool's symbolic name.
7138 * @return {string} Symbolic name of tool
7140 OO
.ui
.Tool
.prototype.getName = function () {
7141 return this.constructor.static.name
;
7147 OO
.ui
.Tool
.prototype.updateTitle = function () {
7148 var titleTooltips
= this.toolGroup
.constructor.static.titleTooltips
,
7149 accelTooltips
= this.toolGroup
.constructor.static.accelTooltips
,
7150 accel
= this.toolbar
.getToolAccelerator( this.constructor.static.name
),
7153 this.$title
.text( this.title
);
7154 this.$accel
.text( accel
);
7156 if ( titleTooltips
&& typeof this.title
=== 'string' && this.title
.length
) {
7157 tooltipParts
.push( this.title
);
7159 if ( accelTooltips
&& typeof accel
=== 'string' && accel
.length
) {
7160 tooltipParts
.push( accel
);
7162 if ( tooltipParts
.length
) {
7163 this.$link
.attr( 'title', tooltipParts
.join( ' ' ) );
7165 this.$link
.removeAttr( 'title' );
7172 * Destroying the tool removes all event handlers and the tool’s DOM elements.
7173 * Call this method whenever you are done using a tool.
7175 OO
.ui
.Tool
.prototype.destroy = function () {
7176 this.toolbar
.disconnect( this );
7177 this.$element
.remove();
7181 * Toolbars are complex interface components that permit users to easily access a variety
7182 * of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional commands that are
7183 * part of the toolbar, but not configured as tools.
7185 * Individual tools are customized and then registered with a {@link OO.ui.ToolFactory tool factory}, which creates
7186 * the tools on demand. Each tool has a symbolic name (used when registering the tool), a title (e.g., ‘Insert
7187 * picture’), and an icon.
7189 * Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be {@link OO.ui.MenuToolGroup menus}
7190 * of tools, {@link OO.ui.ListToolGroup lists} of tools, or a single {@link OO.ui.BarToolGroup bar} of tools.
7191 * The arrangement and order of the toolgroups is customized when the toolbar is set up. Tools can be presented in
7192 * any order, but each can only appear once in the toolbar.
7194 * The following is an example of a basic toolbar.
7197 * // Example of a toolbar
7198 * // Create the toolbar
7199 * var toolFactory = new OO.ui.ToolFactory();
7200 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7201 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7203 * // We will be placing status text in this element when tools are used
7204 * var $area = $( '<p>' ).text( 'Toolbar example' );
7206 * // Define the tools that we're going to place in our toolbar
7208 * // Create a class inheriting from OO.ui.Tool
7209 * function PictureTool() {
7210 * PictureTool.parent.apply( this, arguments );
7212 * OO.inheritClass( PictureTool, OO.ui.Tool );
7213 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7214 * // of 'icon' and 'title' (displayed icon and text).
7215 * PictureTool.static.name = 'picture';
7216 * PictureTool.static.icon = 'picture';
7217 * PictureTool.static.title = 'Insert picture';
7218 * // Defines the action that will happen when this tool is selected (clicked).
7219 * PictureTool.prototype.onSelect = function () {
7220 * $area.text( 'Picture tool clicked!' );
7221 * // Never display this tool as "active" (selected).
7222 * this.setActive( false );
7224 * // Make this tool available in our toolFactory and thus our toolbar
7225 * toolFactory.register( PictureTool );
7227 * // Register two more tools, nothing interesting here
7228 * function SettingsTool() {
7229 * SettingsTool.parent.apply( this, arguments );
7231 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7232 * SettingsTool.static.name = 'settings';
7233 * SettingsTool.static.icon = 'settings';
7234 * SettingsTool.static.title = 'Change settings';
7235 * SettingsTool.prototype.onSelect = function () {
7236 * $area.text( 'Settings tool clicked!' );
7237 * this.setActive( false );
7239 * toolFactory.register( SettingsTool );
7241 * // Register two more tools, nothing interesting here
7242 * function StuffTool() {
7243 * StuffTool.parent.apply( this, arguments );
7245 * OO.inheritClass( StuffTool, OO.ui.Tool );
7246 * StuffTool.static.name = 'stuff';
7247 * StuffTool.static.icon = 'ellipsis';
7248 * StuffTool.static.title = 'More stuff';
7249 * StuffTool.prototype.onSelect = function () {
7250 * $area.text( 'More stuff tool clicked!' );
7251 * this.setActive( false );
7253 * toolFactory.register( StuffTool );
7255 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7256 * // little popup window (a PopupWidget).
7257 * function HelpTool( toolGroup, config ) {
7258 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7263 * this.popup.$body.append( '<p>I am helpful!</p>' );
7265 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7266 * HelpTool.static.name = 'help';
7267 * HelpTool.static.icon = 'help';
7268 * HelpTool.static.title = 'Help';
7269 * toolFactory.register( HelpTool );
7271 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7272 * // used once (but not all defined tools must be used).
7275 * // 'bar' tool groups display tools' icons only, side-by-side.
7277 * include: [ 'picture', 'help' ]
7280 * // 'list' tool groups display both the titles and icons, in a dropdown list.
7282 * indicator: 'down',
7284 * include: [ 'settings', 'stuff' ]
7286 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
7287 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here,
7288 * // since it's more complicated to use. (See the next example snippet on this page.)
7291 * // Create some UI around the toolbar and place it in the document
7292 * var frame = new OO.ui.PanelLayout( {
7296 * var contentFrame = new OO.ui.PanelLayout( {
7300 * frame.$element.append(
7302 * contentFrame.$element.append( $area )
7304 * $( 'body' ).append( frame.$element );
7306 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7308 * toolbar.initialize();
7310 * The following example extends the previous one to illustrate 'menu' toolgroups and the usage of
7311 * 'updateState' event.
7314 * // Create the toolbar
7315 * var toolFactory = new OO.ui.ToolFactory();
7316 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7317 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7319 * // We will be placing status text in this element when tools are used
7320 * var $area = $( '<p>' ).text( 'Toolbar example' );
7322 * // Define the tools that we're going to place in our toolbar
7324 * // Create a class inheriting from OO.ui.Tool
7325 * function PictureTool() {
7326 * PictureTool.parent.apply( this, arguments );
7328 * OO.inheritClass( PictureTool, OO.ui.Tool );
7329 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7330 * // of 'icon' and 'title' (displayed icon and text).
7331 * PictureTool.static.name = 'picture';
7332 * PictureTool.static.icon = 'picture';
7333 * PictureTool.static.title = 'Insert picture';
7334 * // Defines the action that will happen when this tool is selected (clicked).
7335 * PictureTool.prototype.onSelect = function () {
7336 * $area.text( 'Picture tool clicked!' );
7337 * // Never display this tool as "active" (selected).
7338 * this.setActive( false );
7340 * // The toolbar can be synchronized with the state of some external stuff, like a text
7341 * // editor's editing area, highlighting the tools (e.g. a 'bold' tool would be shown as active
7342 * // when the text cursor was inside bolded text). Here we simply disable this feature.
7343 * PictureTool.prototype.onUpdateState = function () {
7345 * // Make this tool available in our toolFactory and thus our toolbar
7346 * toolFactory.register( PictureTool );
7348 * // Register two more tools, nothing interesting here
7349 * function SettingsTool() {
7350 * SettingsTool.parent.apply( this, arguments );
7351 * this.reallyActive = false;
7353 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7354 * SettingsTool.static.name = 'settings';
7355 * SettingsTool.static.icon = 'settings';
7356 * SettingsTool.static.title = 'Change settings';
7357 * SettingsTool.prototype.onSelect = function () {
7358 * $area.text( 'Settings tool clicked!' );
7359 * // Toggle the active state on each click
7360 * this.reallyActive = !this.reallyActive;
7361 * this.setActive( this.reallyActive );
7362 * // To update the menu label
7363 * this.toolbar.emit( 'updateState' );
7365 * SettingsTool.prototype.onUpdateState = function () {
7367 * toolFactory.register( SettingsTool );
7369 * // Register two more tools, nothing interesting here
7370 * function StuffTool() {
7371 * StuffTool.parent.apply( this, arguments );
7372 * this.reallyActive = false;
7374 * OO.inheritClass( StuffTool, OO.ui.Tool );
7375 * StuffTool.static.name = 'stuff';
7376 * StuffTool.static.icon = 'ellipsis';
7377 * StuffTool.static.title = 'More stuff';
7378 * StuffTool.prototype.onSelect = function () {
7379 * $area.text( 'More stuff tool clicked!' );
7380 * // Toggle the active state on each click
7381 * this.reallyActive = !this.reallyActive;
7382 * this.setActive( this.reallyActive );
7383 * // To update the menu label
7384 * this.toolbar.emit( 'updateState' );
7386 * StuffTool.prototype.onUpdateState = function () {
7388 * toolFactory.register( StuffTool );
7390 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7391 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
7392 * function HelpTool( toolGroup, config ) {
7393 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7398 * this.popup.$body.append( '<p>I am helpful!</p>' );
7400 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7401 * HelpTool.static.name = 'help';
7402 * HelpTool.static.icon = 'help';
7403 * HelpTool.static.title = 'Help';
7404 * toolFactory.register( HelpTool );
7406 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7407 * // used once (but not all defined tools must be used).
7410 * // 'bar' tool groups display tools' icons only, side-by-side.
7412 * include: [ 'picture', 'help' ]
7415 * // 'menu' tool groups display both the titles and icons, in a dropdown menu.
7416 * // Menu label indicates which items are selected.
7418 * indicator: 'down',
7419 * include: [ 'settings', 'stuff' ]
7423 * // Create some UI around the toolbar and place it in the document
7424 * var frame = new OO.ui.PanelLayout( {
7428 * var contentFrame = new OO.ui.PanelLayout( {
7432 * frame.$element.append(
7434 * contentFrame.$element.append( $area )
7436 * $( 'body' ).append( frame.$element );
7438 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7440 * toolbar.initialize();
7441 * toolbar.emit( 'updateState' );
7444 * @extends OO.ui.Element
7445 * @mixins OO.EventEmitter
7446 * @mixins OO.ui.mixin.GroupElement
7449 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
7450 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups
7451 * @param {Object} [config] Configuration options
7452 * @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are included
7453 * in the toolbar, but are not configured as tools. By default, actions are displayed on the right side of
7455 * @cfg {boolean} [shadow] Add a shadow below the toolbar.
7457 OO
.ui
.Toolbar
= function OoUiToolbar( toolFactory
, toolGroupFactory
, config
) {
7458 // Allow passing positional parameters inside the config object
7459 if ( OO
.isPlainObject( toolFactory
) && config
=== undefined ) {
7460 config
= toolFactory
;
7461 toolFactory
= config
.toolFactory
;
7462 toolGroupFactory
= config
.toolGroupFactory
;
7465 // Configuration initialization
7466 config
= config
|| {};
7468 // Parent constructor
7469 OO
.ui
.Toolbar
.parent
.call( this, config
);
7471 // Mixin constructors
7472 OO
.EventEmitter
.call( this );
7473 OO
.ui
.mixin
.GroupElement
.call( this, config
);
7476 this.toolFactory
= toolFactory
;
7477 this.toolGroupFactory
= toolGroupFactory
;
7480 this.$bar
= $( '<div>' );
7481 this.$actions
= $( '<div>' );
7482 this.initialized
= false;
7483 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
7487 .add( this.$bar
).add( this.$group
).add( this.$actions
)
7488 .on( 'mousedown keydown', this.onPointerDown
.bind( this ) );
7491 this.$group
.addClass( 'oo-ui-toolbar-tools' );
7492 if ( config
.actions
) {
7493 this.$bar
.append( this.$actions
.addClass( 'oo-ui-toolbar-actions' ) );
7496 .addClass( 'oo-ui-toolbar-bar' )
7497 .append( this.$group
, '<div style="clear:both"></div>' );
7498 if ( config
.shadow
) {
7499 this.$bar
.append( '<div class="oo-ui-toolbar-shadow"></div>' );
7501 this.$element
.addClass( 'oo-ui-toolbar' ).append( this.$bar
);
7506 OO
.inheritClass( OO
.ui
.Toolbar
, OO
.ui
.Element
);
7507 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.EventEmitter
);
7508 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.ui
.mixin
.GroupElement
);
7513 * Get the tool factory.
7515 * @return {OO.ui.ToolFactory} Tool factory
7517 OO
.ui
.Toolbar
.prototype.getToolFactory = function () {
7518 return this.toolFactory
;
7522 * Get the toolgroup factory.
7524 * @return {OO.Factory} Toolgroup factory
7526 OO
.ui
.Toolbar
.prototype.getToolGroupFactory = function () {
7527 return this.toolGroupFactory
;
7531 * Handles mouse down events.
7534 * @param {jQuery.Event} e Mouse down event
7536 OO
.ui
.Toolbar
.prototype.onPointerDown = function ( e
) {
7537 var $closestWidgetToEvent
= $( e
.target
).closest( '.oo-ui-widget' ),
7538 $closestWidgetToToolbar
= this.$element
.closest( '.oo-ui-widget' );
7539 if ( !$closestWidgetToEvent
.length
|| $closestWidgetToEvent
[ 0 ] === $closestWidgetToToolbar
[ 0 ] ) {
7545 * Handle window resize event.
7548 * @param {jQuery.Event} e Window resize event
7550 OO
.ui
.Toolbar
.prototype.onWindowResize = function () {
7551 this.$element
.toggleClass(
7552 'oo-ui-toolbar-narrow',
7553 this.$bar
.width() <= this.narrowThreshold
7558 * Sets up handles and preloads required information for the toolbar to work.
7559 * This must be called after it is attached to a visible document and before doing anything else.
7561 OO
.ui
.Toolbar
.prototype.initialize = function () {
7562 this.initialized
= true;
7563 this.narrowThreshold
= this.$group
.width() + this.$actions
.width();
7564 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
7565 this.onWindowResize();
7569 * Set up the toolbar.
7571 * The toolbar is set up with a list of toolgroup configurations that specify the type of
7572 * toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or {@link OO.ui.ListToolGroup list})
7573 * to add and which tools to include, exclude, promote, or demote within that toolgroup. Please
7574 * see {@link OO.ui.ToolGroup toolgroups} for more information about including tools in toolgroups.
7576 * @param {Object.<string,Array>} groups List of toolgroup configurations
7577 * @param {Array|string} [groups.include] Tools to include in the toolgroup
7578 * @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup
7579 * @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup
7580 * @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup
7582 OO
.ui
.Toolbar
.prototype.setup = function ( groups
) {
7583 var i
, len
, type
, group
,
7585 defaultType
= 'bar';
7587 // Cleanup previous groups
7590 // Build out new groups
7591 for ( i
= 0, len
= groups
.length
; i
< len
; i
++ ) {
7592 group
= groups
[ i
];
7593 if ( group
.include
=== '*' ) {
7594 // Apply defaults to catch-all groups
7595 if ( group
.type
=== undefined ) {
7596 group
.type
= 'list';
7598 if ( group
.label
=== undefined ) {
7599 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
7602 // Check type has been registered
7603 type
= this.getToolGroupFactory().lookup( group
.type
) ? group
.type
: defaultType
;
7605 this.getToolGroupFactory().create( type
, this, group
)
7608 this.addItems( items
);
7612 * Remove all tools and toolgroups from the toolbar.
7614 OO
.ui
.Toolbar
.prototype.reset = function () {
7619 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
7620 this.items
[ i
].destroy();
7626 * Destroy the toolbar.
7628 * Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. Call
7629 * this method whenever you are done using a toolbar.
7631 OO
.ui
.Toolbar
.prototype.destroy = function () {
7632 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
7634 this.$element
.remove();
7638 * Check if the tool is available.
7640 * Available tools are ones that have not yet been added to the toolbar.
7642 * @param {string} name Symbolic name of tool
7643 * @return {boolean} Tool is available
7645 OO
.ui
.Toolbar
.prototype.isToolAvailable = function ( name
) {
7646 return !this.tools
[ name
];
7650 * Prevent tool from being used again.
7652 * @param {OO.ui.Tool} tool Tool to reserve
7654 OO
.ui
.Toolbar
.prototype.reserveTool = function ( tool
) {
7655 this.tools
[ tool
.getName() ] = tool
;
7659 * Allow tool to be used again.
7661 * @param {OO.ui.Tool} tool Tool to release
7663 OO
.ui
.Toolbar
.prototype.releaseTool = function ( tool
) {
7664 delete this.tools
[ tool
.getName() ];
7668 * Get accelerator label for tool.
7670 * The OOjs UI library does not contain an accelerator system, but this is the hook for one. To
7671 * use an accelerator system, subclass the toolbar and override this method, which is meant to return a label
7672 * that describes the accelerator keys for the tool passed (by symbolic name) to the method.
7674 * @param {string} name Symbolic name of tool
7675 * @return {string|undefined} Tool accelerator label if available
7677 OO
.ui
.Toolbar
.prototype.getToolAccelerator = function () {
7682 * ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a {@link OO.ui.Toolbar toolbar}.
7683 * The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or {@link OO.ui.MenuToolGroup menu})
7684 * to which a tool belongs determines how the tool is arranged and displayed in the toolbar. Toolgroups
7685 * themselves are created on demand with a {@link OO.ui.ToolGroupFactory toolgroup factory}.
7687 * Toolgroups can contain individual tools, groups of tools, or all available tools:
7689 * To include an individual tool (or array of individual tools), specify tools by symbolic name:
7691 * include: [ 'tool-name' ] or [ { name: 'tool-name' }]
7693 * 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.)
7695 * include: [ { group: 'group-name' } ]
7697 * To include all tools that are not yet assigned to a toolgroup, use the catch-all selector, an asterisk (*):
7701 * See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in general,
7702 * please see the [OOjs UI documentation on MediaWiki][1].
7704 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7708 * @extends OO.ui.Widget
7709 * @mixins OO.ui.mixin.GroupElement
7712 * @param {OO.ui.Toolbar} toolbar
7713 * @param {Object} [config] Configuration options
7714 * @cfg {Array|string} [include=[]] List of tools to include in the toolgroup.
7715 * @cfg {Array|string} [exclude=[]] List of tools to exclude from the toolgroup.
7716 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning of the toolgroup.
7717 * @cfg {Array|string} [demote=[]] List of tools to demote to the end of the toolgroup.
7718 * This setting is particularly useful when tools have been added to the toolgroup
7719 * en masse (e.g., via the catch-all selector).
7721 OO
.ui
.ToolGroup
= function OoUiToolGroup( toolbar
, config
) {
7722 // Allow passing positional parameters inside the config object
7723 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
7725 toolbar
= config
.toolbar
;
7728 // Configuration initialization
7729 config
= config
|| {};
7731 // Parent constructor
7732 OO
.ui
.ToolGroup
.parent
.call( this, config
);
7734 // Mixin constructors
7735 OO
.ui
.mixin
.GroupElement
.call( this, config
);
7738 this.toolbar
= toolbar
;
7740 this.pressed
= null;
7741 this.autoDisabled
= false;
7742 this.include
= config
.include
|| [];
7743 this.exclude
= config
.exclude
|| [];
7744 this.promote
= config
.promote
|| [];
7745 this.demote
= config
.demote
|| [];
7746 this.onCapturedMouseKeyUpHandler
= this.onCapturedMouseKeyUp
.bind( this );
7750 mousedown
: this.onMouseKeyDown
.bind( this ),
7751 mouseup
: this.onMouseKeyUp
.bind( this ),
7752 keydown
: this.onMouseKeyDown
.bind( this ),
7753 keyup
: this.onMouseKeyUp
.bind( this ),
7754 focus
: this.onMouseOverFocus
.bind( this ),
7755 blur
: this.onMouseOutBlur
.bind( this ),
7756 mouseover
: this.onMouseOverFocus
.bind( this ),
7757 mouseout
: this.onMouseOutBlur
.bind( this )
7759 this.toolbar
.getToolFactory().connect( this, { register
: 'onToolFactoryRegister' } );
7760 this.aggregate( { disable
: 'itemDisable' } );
7761 this.connect( this, { itemDisable
: 'updateDisabled' } );
7764 this.$group
.addClass( 'oo-ui-toolGroup-tools' );
7766 .addClass( 'oo-ui-toolGroup' )
7767 .append( this.$group
);
7773 OO
.inheritClass( OO
.ui
.ToolGroup
, OO
.ui
.Widget
);
7774 OO
.mixinClass( OO
.ui
.ToolGroup
, OO
.ui
.mixin
.GroupElement
);
7782 /* Static Properties */
7785 * Show labels in tooltips.
7789 * @property {boolean}
7791 OO
.ui
.ToolGroup
.static.titleTooltips
= false;
7794 * Show acceleration labels in tooltips.
7796 * Note: The OOjs UI library does not include an accelerator system, but does contain
7797 * a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and
7798 * override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is
7799 * meant to return a label that describes the accelerator keys for a given tool (e.g., 'Ctrl + M').
7803 * @property {boolean}
7805 OO
.ui
.ToolGroup
.static.accelTooltips
= false;
7808 * Automatically disable the toolgroup when all tools are disabled
7812 * @property {boolean}
7814 OO
.ui
.ToolGroup
.static.autoDisable
= true;
7821 OO
.ui
.ToolGroup
.prototype.isDisabled = function () {
7822 return this.autoDisabled
|| OO
.ui
.ToolGroup
.parent
.prototype.isDisabled
.apply( this, arguments
);
7828 OO
.ui
.ToolGroup
.prototype.updateDisabled = function () {
7829 var i
, item
, allDisabled
= true;
7831 if ( this.constructor.static.autoDisable
) {
7832 for ( i
= this.items
.length
- 1; i
>= 0; i
-- ) {
7833 item
= this.items
[ i
];
7834 if ( !item
.isDisabled() ) {
7835 allDisabled
= false;
7839 this.autoDisabled
= allDisabled
;
7841 OO
.ui
.ToolGroup
.parent
.prototype.updateDisabled
.apply( this, arguments
);
7845 * Handle mouse down and key down events.
7848 * @param {jQuery.Event} e Mouse down or key down event
7850 OO
.ui
.ToolGroup
.prototype.onMouseKeyDown = function ( e
) {
7852 !this.isDisabled() &&
7853 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
7855 this.pressed
= this.getTargetTool( e
);
7856 if ( this.pressed
) {
7857 this.pressed
.setActive( true );
7858 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler
);
7859 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler
);
7866 * Handle captured mouse up and key up events.
7869 * @param {Event} e Mouse up or key up event
7871 OO
.ui
.ToolGroup
.prototype.onCapturedMouseKeyUp = function ( e
) {
7872 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler
);
7873 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler
);
7874 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
7875 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
7876 this.onMouseKeyUp( e
);
7880 * Handle mouse up and key up events.
7883 * @param {jQuery.Event} e Mouse up or key up event
7885 OO
.ui
.ToolGroup
.prototype.onMouseKeyUp = function ( e
) {
7886 var tool
= this.getTargetTool( e
);
7889 !this.isDisabled() && this.pressed
&& this.pressed
=== tool
&&
7890 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
7892 this.pressed
.onSelect();
7893 this.pressed
= null;
7897 this.pressed
= null;
7901 * Handle mouse over and focus events.
7904 * @param {jQuery.Event} e Mouse over or focus event
7906 OO
.ui
.ToolGroup
.prototype.onMouseOverFocus = function ( e
) {
7907 var tool
= this.getTargetTool( e
);
7909 if ( this.pressed
&& this.pressed
=== tool
) {
7910 this.pressed
.setActive( true );
7915 * Handle mouse out and blur events.
7918 * @param {jQuery.Event} e Mouse out or blur event
7920 OO
.ui
.ToolGroup
.prototype.onMouseOutBlur = function ( e
) {
7921 var tool
= this.getTargetTool( e
);
7923 if ( this.pressed
&& this.pressed
=== tool
) {
7924 this.pressed
.setActive( false );
7929 * Get the closest tool to a jQuery.Event.
7931 * Only tool links are considered, which prevents other elements in the tool such as popups from
7932 * triggering tool group interactions.
7935 * @param {jQuery.Event} e
7936 * @return {OO.ui.Tool|null} Tool, `null` if none was found
7938 OO
.ui
.ToolGroup
.prototype.getTargetTool = function ( e
) {
7940 $item
= $( e
.target
).closest( '.oo-ui-tool-link' );
7942 if ( $item
.length
) {
7943 tool
= $item
.parent().data( 'oo-ui-tool' );
7946 return tool
&& !tool
.isDisabled() ? tool
: null;
7950 * Handle tool registry register events.
7952 * If a tool is registered after the group is created, we must repopulate the list to account for:
7954 * - a tool being added that may be included
7955 * - a tool already included being overridden
7958 * @param {string} name Symbolic name of tool
7960 OO
.ui
.ToolGroup
.prototype.onToolFactoryRegister = function () {
7965 * Get the toolbar that contains the toolgroup.
7967 * @return {OO.ui.Toolbar} Toolbar that contains the toolgroup
7969 OO
.ui
.ToolGroup
.prototype.getToolbar = function () {
7970 return this.toolbar
;
7974 * Add and remove tools based on configuration.
7976 OO
.ui
.ToolGroup
.prototype.populate = function () {
7977 var i
, len
, name
, tool
,
7978 toolFactory
= this.toolbar
.getToolFactory(),
7982 list
= this.toolbar
.getToolFactory().getTools(
7983 this.include
, this.exclude
, this.promote
, this.demote
7986 // Build a list of needed tools
7987 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
7991 toolFactory
.lookup( name
) &&
7992 // Tool is available or is already in this group
7993 ( this.toolbar
.isToolAvailable( name
) || this.tools
[ name
] )
7995 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
7996 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
7997 this.toolbar
.tools
[ name
] = true;
7998 tool
= this.tools
[ name
];
8000 // Auto-initialize tools on first use
8001 this.tools
[ name
] = tool
= toolFactory
.create( name
, this );
8004 this.toolbar
.reserveTool( tool
);
8006 names
[ name
] = true;
8009 // Remove tools that are no longer needed
8010 for ( name
in this.tools
) {
8011 if ( !names
[ name
] ) {
8012 this.tools
[ name
].destroy();
8013 this.toolbar
.releaseTool( this.tools
[ name
] );
8014 remove
.push( this.tools
[ name
] );
8015 delete this.tools
[ name
];
8018 if ( remove
.length
) {
8019 this.removeItems( remove
);
8021 // Update emptiness state
8023 this.$element
.removeClass( 'oo-ui-toolGroup-empty' );
8025 this.$element
.addClass( 'oo-ui-toolGroup-empty' );
8027 // Re-add tools (moving existing ones to new locations)
8028 this.addItems( add
);
8029 // Disabled state may depend on items
8030 this.updateDisabled();
8034 * Destroy toolgroup.
8036 OO
.ui
.ToolGroup
.prototype.destroy = function () {
8040 this.toolbar
.getToolFactory().disconnect( this );
8041 for ( name
in this.tools
) {
8042 this.toolbar
.releaseTool( this.tools
[ name
] );
8043 this.tools
[ name
].disconnect( this ).destroy();
8044 delete this.tools
[ name
];
8046 this.$element
.remove();
8050 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
8051 * consists of a header that contains the dialog title, a body with the message, and a footer that
8052 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
8053 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
8055 * There are two basic types of message dialogs, confirmation and alert:
8057 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
8058 * more details about the consequences.
8059 * - **alert**: the dialog title describes which event occurred and the message provides more information
8060 * about why the event occurred.
8062 * The MessageDialog class specifies two actions: ‘accept’, the primary
8063 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
8064 * passing along the selected action.
8066 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
8069 * // Example: Creating and opening a message dialog window.
8070 * var messageDialog = new OO.ui.MessageDialog();
8072 * // Create and append a window manager.
8073 * var windowManager = new OO.ui.WindowManager();
8074 * $( 'body' ).append( windowManager.$element );
8075 * windowManager.addWindows( [ messageDialog ] );
8076 * // Open the window.
8077 * windowManager.openWindow( messageDialog, {
8078 * title: 'Basic message dialog',
8079 * message: 'This is the message'
8082 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
8085 * @extends OO.ui.Dialog
8088 * @param {Object} [config] Configuration options
8090 OO
.ui
.MessageDialog
= function OoUiMessageDialog( config
) {
8091 // Parent constructor
8092 OO
.ui
.MessageDialog
.parent
.call( this, config
);
8095 this.verticalActionLayout
= null;
8098 this.$element
.addClass( 'oo-ui-messageDialog' );
8103 OO
.inheritClass( OO
.ui
.MessageDialog
, OO
.ui
.Dialog
);
8105 /* Static Properties */
8107 OO
.ui
.MessageDialog
.static.name
= 'message';
8109 OO
.ui
.MessageDialog
.static.size
= 'small';
8111 OO
.ui
.MessageDialog
.static.verbose
= false;
8116 * The title of a confirmation dialog describes what a progressive action will do. The
8117 * title of an alert dialog describes which event occurred.
8121 * @property {jQuery|string|Function|null}
8123 OO
.ui
.MessageDialog
.static.title
= null;
8126 * The message displayed in the dialog body.
8128 * A confirmation message describes the consequences of a progressive action. An alert
8129 * message describes why an event occurred.
8133 * @property {jQuery|string|Function|null}
8135 OO
.ui
.MessageDialog
.static.message
= null;
8137 OO
.ui
.MessageDialog
.static.actions
= [
8138 { action
: 'accept', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-accept' ), flags
: 'primary' },
8139 { action
: 'reject', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-reject' ), flags
: 'safe' }
8147 OO
.ui
.MessageDialog
.prototype.setManager = function ( manager
) {
8148 OO
.ui
.MessageDialog
.parent
.prototype.setManager
.call( this, manager
);
8151 this.manager
.connect( this, {
8161 OO
.ui
.MessageDialog
.prototype.onActionResize = function ( action
) {
8163 return OO
.ui
.MessageDialog
.parent
.prototype.onActionResize
.call( this, action
);
8167 * Handle window resized events.
8171 OO
.ui
.MessageDialog
.prototype.onResize = function () {
8173 dialog
.fitActions();
8174 // Wait for CSS transition to finish and do it again :(
8175 setTimeout( function () {
8176 dialog
.fitActions();
8181 * Toggle action layout between vertical and horizontal.
8185 * @param {boolean} [value] Layout actions vertically, omit to toggle
8188 OO
.ui
.MessageDialog
.prototype.toggleVerticalActionLayout = function ( value
) {
8189 value
= value
=== undefined ? !this.verticalActionLayout
: !!value
;
8191 if ( value
!== this.verticalActionLayout
) {
8192 this.verticalActionLayout
= value
;
8194 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value
)
8195 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value
);
8204 OO
.ui
.MessageDialog
.prototype.getActionProcess = function ( action
) {
8206 return new OO
.ui
.Process( function () {
8207 this.close( { action
: action
} );
8210 return OO
.ui
.MessageDialog
.parent
.prototype.getActionProcess
.call( this, action
);
8216 * @param {Object} [data] Dialog opening data
8217 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
8218 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
8219 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
8220 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
8223 OO
.ui
.MessageDialog
.prototype.getSetupProcess = function ( data
) {
8227 return OO
.ui
.MessageDialog
.parent
.prototype.getSetupProcess
.call( this, data
)
8228 .next( function () {
8229 this.title
.setLabel(
8230 data
.title
!== undefined ? data
.title
: this.constructor.static.title
8232 this.message
.setLabel(
8233 data
.message
!== undefined ? data
.message
: this.constructor.static.message
8235 this.message
.$element
.toggleClass(
8236 'oo-ui-messageDialog-message-verbose',
8237 data
.verbose
!== undefined ? data
.verbose
: this.constructor.static.verbose
8245 OO
.ui
.MessageDialog
.prototype.getReadyProcess = function ( data
) {
8249 return OO
.ui
.MessageDialog
.parent
.prototype.getReadyProcess
.call( this, data
)
8250 .next( function () {
8251 // Focus the primary action button
8252 var actions
= this.actions
.get();
8253 actions
= actions
.filter( function ( action
) {
8254 return action
.getFlags().indexOf( 'primary' ) > -1;
8256 if ( actions
.length
> 0 ) {
8257 actions
[ 0 ].$button
.focus();
8265 OO
.ui
.MessageDialog
.prototype.getBodyHeight = function () {
8266 var bodyHeight
, oldOverflow
,
8267 $scrollable
= this.container
.$element
;
8269 oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
8270 $scrollable
[ 0 ].style
.overflow
= 'hidden';
8272 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
8274 bodyHeight
= this.text
.$element
.outerHeight( true );
8275 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
8283 OO
.ui
.MessageDialog
.prototype.setDimensions = function ( dim
) {
8284 var $scrollable
= this.container
.$element
;
8285 OO
.ui
.MessageDialog
.parent
.prototype.setDimensions
.call( this, dim
);
8287 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
8288 // Need to do it after transition completes (250ms), add 50ms just in case.
8289 setTimeout( function () {
8290 var oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
8291 $scrollable
[ 0 ].style
.overflow
= 'hidden';
8293 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
8295 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
8304 OO
.ui
.MessageDialog
.prototype.initialize = function () {
8306 OO
.ui
.MessageDialog
.parent
.prototype.initialize
.call( this );
8309 this.$actions
= $( '<div>' );
8310 this.container
= new OO
.ui
.PanelLayout( {
8311 scrollable
: true, classes
: [ 'oo-ui-messageDialog-container' ]
8313 this.text
= new OO
.ui
.PanelLayout( {
8314 padded
: true, expanded
: false, classes
: [ 'oo-ui-messageDialog-text' ]
8316 this.message
= new OO
.ui
.LabelWidget( {
8317 classes
: [ 'oo-ui-messageDialog-message' ]
8321 this.title
.$element
.addClass( 'oo-ui-messageDialog-title' );
8322 this.$content
.addClass( 'oo-ui-messageDialog-content' );
8323 this.container
.$element
.append( this.text
.$element
);
8324 this.text
.$element
.append( this.title
.$element
, this.message
.$element
);
8325 this.$body
.append( this.container
.$element
);
8326 this.$actions
.addClass( 'oo-ui-messageDialog-actions' );
8327 this.$foot
.append( this.$actions
);
8333 OO
.ui
.MessageDialog
.prototype.attachActions = function () {
8334 var i
, len
, other
, special
, others
;
8337 OO
.ui
.MessageDialog
.parent
.prototype.attachActions
.call( this );
8339 special
= this.actions
.getSpecial();
8340 others
= this.actions
.getOthers();
8342 if ( special
.safe
) {
8343 this.$actions
.append( special
.safe
.$element
);
8344 special
.safe
.toggleFramed( false );
8346 if ( others
.length
) {
8347 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
8348 other
= others
[ i
];
8349 this.$actions
.append( other
.$element
);
8350 other
.toggleFramed( false );
8353 if ( special
.primary
) {
8354 this.$actions
.append( special
.primary
.$element
);
8355 special
.primary
.toggleFramed( false );
8358 if ( !this.isOpening() ) {
8359 // If the dialog is currently opening, this will be called automatically soon.
8360 // This also calls #fitActions.
8366 * Fit action actions into columns or rows.
8368 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
8372 OO
.ui
.MessageDialog
.prototype.fitActions = function () {
8374 previous
= this.verticalActionLayout
,
8375 actions
= this.actions
.get();
8378 this.toggleVerticalActionLayout( false );
8379 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
8380 action
= actions
[ i
];
8381 if ( action
.$element
.innerWidth() < action
.$label
.outerWidth( true ) ) {
8382 this.toggleVerticalActionLayout( true );
8387 // Move the body out of the way of the foot
8388 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
8390 if ( this.verticalActionLayout
!== previous
) {
8391 // We changed the layout, window height might need to be updated.
8397 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
8398 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
8399 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
8400 * relevant. The ProcessDialog class is always extended and customized with the actions and content
8401 * required for each process.
8403 * The process dialog box consists of a header that visually represents the ‘working’ state of long
8404 * processes with an animation. The header contains the dialog title as well as
8405 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
8406 * a ‘primary’ action on the right (e.g., ‘Done’).
8408 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
8409 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
8412 * // Example: Creating and opening a process dialog window.
8413 * function MyProcessDialog( config ) {
8414 * MyProcessDialog.parent.call( this, config );
8416 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
8418 * MyProcessDialog.static.title = 'Process dialog';
8419 * MyProcessDialog.static.actions = [
8420 * { action: 'save', label: 'Done', flags: 'primary' },
8421 * { label: 'Cancel', flags: 'safe' }
8424 * MyProcessDialog.prototype.initialize = function () {
8425 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
8426 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
8427 * 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>' );
8428 * this.$body.append( this.content.$element );
8430 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
8431 * var dialog = this;
8433 * return new OO.ui.Process( function () {
8434 * dialog.close( { action: action } );
8437 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
8440 * var windowManager = new OO.ui.WindowManager();
8441 * $( 'body' ).append( windowManager.$element );
8443 * var dialog = new MyProcessDialog();
8444 * windowManager.addWindows( [ dialog ] );
8445 * windowManager.openWindow( dialog );
8447 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
8451 * @extends OO.ui.Dialog
8454 * @param {Object} [config] Configuration options
8456 OO
.ui
.ProcessDialog
= function OoUiProcessDialog( config
) {
8457 // Parent constructor
8458 OO
.ui
.ProcessDialog
.parent
.call( this, config
);
8461 this.fitOnOpen
= false;
8464 this.$element
.addClass( 'oo-ui-processDialog' );
8469 OO
.inheritClass( OO
.ui
.ProcessDialog
, OO
.ui
.Dialog
);
8474 * Handle dismiss button click events.
8480 OO
.ui
.ProcessDialog
.prototype.onDismissErrorButtonClick = function () {
8485 * Handle retry button click events.
8487 * Hides errors and then tries again.
8491 OO
.ui
.ProcessDialog
.prototype.onRetryButtonClick = function () {
8493 this.executeAction( this.currentAction
);
8499 OO
.ui
.ProcessDialog
.prototype.onActionResize = function ( action
) {
8500 if ( this.actions
.isSpecial( action
) ) {
8503 return OO
.ui
.ProcessDialog
.parent
.prototype.onActionResize
.call( this, action
);
8509 OO
.ui
.ProcessDialog
.prototype.initialize = function () {
8511 OO
.ui
.ProcessDialog
.parent
.prototype.initialize
.call( this );
8514 this.$navigation
= $( '<div>' );
8515 this.$location
= $( '<div>' );
8516 this.$safeActions
= $( '<div>' );
8517 this.$primaryActions
= $( '<div>' );
8518 this.$otherActions
= $( '<div>' );
8519 this.dismissButton
= new OO
.ui
.ButtonWidget( {
8520 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' )
8522 this.retryButton
= new OO
.ui
.ButtonWidget();
8523 this.$errors
= $( '<div>' );
8524 this.$errorsTitle
= $( '<div>' );
8527 this.dismissButton
.connect( this, { click
: 'onDismissErrorButtonClick' } );
8528 this.retryButton
.connect( this, { click
: 'onRetryButtonClick' } );
8531 this.title
.$element
.addClass( 'oo-ui-processDialog-title' );
8533 .append( this.title
.$element
)
8534 .addClass( 'oo-ui-processDialog-location' );
8535 this.$safeActions
.addClass( 'oo-ui-processDialog-actions-safe' );
8536 this.$primaryActions
.addClass( 'oo-ui-processDialog-actions-primary' );
8537 this.$otherActions
.addClass( 'oo-ui-processDialog-actions-other' );
8539 .addClass( 'oo-ui-processDialog-errors-title' )
8540 .text( OO
.ui
.msg( 'ooui-dialog-process-error' ) );
8542 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
8543 .append( this.$errorsTitle
, this.dismissButton
.$element
, this.retryButton
.$element
);
8545 .addClass( 'oo-ui-processDialog-content' )
8546 .append( this.$errors
);
8548 .addClass( 'oo-ui-processDialog-navigation' )
8549 .append( this.$safeActions
, this.$location
, this.$primaryActions
);
8550 this.$head
.append( this.$navigation
);
8551 this.$foot
.append( this.$otherActions
);
8557 OO
.ui
.ProcessDialog
.prototype.getActionWidgets = function ( actions
) {
8558 var i
, len
, widgets
= [];
8559 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
8561 new OO
.ui
.ActionWidget( $.extend( { framed
: true }, actions
[ i
] ) )
8570 OO
.ui
.ProcessDialog
.prototype.attachActions = function () {
8571 var i
, len
, other
, special
, others
;
8574 OO
.ui
.ProcessDialog
.parent
.prototype.attachActions
.call( this );
8576 special
= this.actions
.getSpecial();
8577 others
= this.actions
.getOthers();
8578 if ( special
.primary
) {
8579 this.$primaryActions
.append( special
.primary
.$element
);
8581 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
8582 other
= others
[ i
];
8583 this.$otherActions
.append( other
.$element
);
8585 if ( special
.safe
) {
8586 this.$safeActions
.append( special
.safe
.$element
);
8590 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
8596 OO
.ui
.ProcessDialog
.prototype.executeAction = function ( action
) {
8598 return OO
.ui
.ProcessDialog
.parent
.prototype.executeAction
.call( this, action
)
8599 .fail( function ( errors
) {
8600 process
.showErrors( errors
|| [] );
8607 OO
.ui
.ProcessDialog
.prototype.setDimensions = function () {
8609 OO
.ui
.ProcessDialog
.parent
.prototype.setDimensions
.apply( this, arguments
);
8615 * Fit label between actions.
8620 OO
.ui
.ProcessDialog
.prototype.fitLabel = function () {
8621 var safeWidth
, primaryWidth
, biggerWidth
, labelWidth
, navigationWidth
, leftWidth
, rightWidth
,
8622 size
= this.getSizeProperties();
8624 if ( typeof size
.width
!== 'number' ) {
8625 if ( this.isOpened() ) {
8626 navigationWidth
= this.$head
.width() - 20;
8627 } else if ( this.isOpening() ) {
8628 if ( !this.fitOnOpen
) {
8629 // Size is relative and the dialog isn't open yet, so wait.
8630 this.manager
.opening
.done( this.fitLabel
.bind( this ) );
8631 this.fitOnOpen
= true;
8638 navigationWidth
= size
.width
- 20;
8641 safeWidth
= this.$safeActions
.is( ':visible' ) ? this.$safeActions
.width() : 0;
8642 primaryWidth
= this.$primaryActions
.is( ':visible' ) ? this.$primaryActions
.width() : 0;
8643 biggerWidth
= Math
.max( safeWidth
, primaryWidth
);
8645 labelWidth
= this.title
.$element
.width();
8647 if ( 2 * biggerWidth
+ labelWidth
< navigationWidth
) {
8648 // We have enough space to center the label
8649 leftWidth
= rightWidth
= biggerWidth
;
8651 // Let's hope we at least have enough space not to overlap, because we can't wrap the label…
8652 if ( this.getDir() === 'ltr' ) {
8653 leftWidth
= safeWidth
;
8654 rightWidth
= primaryWidth
;
8656 leftWidth
= primaryWidth
;
8657 rightWidth
= safeWidth
;
8661 this.$location
.css( { paddingLeft
: leftWidth
, paddingRight
: rightWidth
} );
8667 * Handle errors that occurred during accept or reject processes.
8670 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
8672 OO
.ui
.ProcessDialog
.prototype.showErrors = function ( errors
) {
8673 var i
, len
, $item
, actions
,
8679 if ( errors
instanceof OO
.ui
.Error
) {
8680 errors
= [ errors
];
8683 for ( i
= 0, len
= errors
.length
; i
< len
; i
++ ) {
8684 if ( !errors
[ i
].isRecoverable() ) {
8685 recoverable
= false;
8687 if ( errors
[ i
].isWarning() ) {
8690 $item
= $( '<div>' )
8691 .addClass( 'oo-ui-processDialog-error' )
8692 .append( errors
[ i
].getMessage() );
8693 items
.push( $item
[ 0 ] );
8695 this.$errorItems
= $( items
);
8696 if ( recoverable
) {
8697 abilities
[ this.currentAction
] = true;
8698 // Copy the flags from the first matching action
8699 actions
= this.actions
.get( { actions
: this.currentAction
} );
8700 if ( actions
.length
) {
8701 this.retryButton
.clearFlags().setFlags( actions
[ 0 ].getFlags() );
8704 abilities
[ this.currentAction
] = false;
8705 this.actions
.setAbilities( abilities
);
8708 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-continue' ) );
8710 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-retry' ) );
8712 this.retryButton
.toggle( recoverable
);
8713 this.$errorsTitle
.after( this.$errorItems
);
8714 this.$errors
.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
8722 OO
.ui
.ProcessDialog
.prototype.hideErrors = function () {
8723 this.$errors
.addClass( 'oo-ui-element-hidden' );
8724 if ( this.$errorItems
) {
8725 this.$errorItems
.remove();
8726 this.$errorItems
= null;
8733 OO
.ui
.ProcessDialog
.prototype.getTeardownProcess = function ( data
) {
8735 return OO
.ui
.ProcessDialog
.parent
.prototype.getTeardownProcess
.call( this, data
)
8736 .first( function () {
8737 // Make sure to hide errors
8739 this.fitOnOpen
= false;
8744 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
8745 * which is a widget that is specified by reference before any optional configuration settings.
8747 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
8749 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8750 * A left-alignment is used for forms with many fields.
8751 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8752 * A right-alignment is used for long but familiar forms which users tab through,
8753 * verifying the current field with a quick glance at the label.
8754 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8755 * that users fill out from top to bottom.
8756 * - **inline**: The label is placed after the field-widget and aligned to the left.
8757 * An inline-alignment is best used with checkboxes or radio buttons.
8759 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
8760 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
8762 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8764 * @extends OO.ui.Layout
8765 * @mixins OO.ui.mixin.LabelElement
8766 * @mixins OO.ui.mixin.TitledElement
8769 * @param {OO.ui.Widget} fieldWidget Field widget
8770 * @param {Object} [config] Configuration options
8771 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
8772 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
8773 * The array may contain strings or OO.ui.HtmlSnippet instances.
8774 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
8775 * The array may contain strings or OO.ui.HtmlSnippet instances.
8776 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
8777 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
8778 * For important messages, you are advised to use `notices`, as they are always shown.
8780 * @throws {Error} An error is thrown if no widget is specified
8782 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
8783 var hasInputWidget
, div
, i
;
8785 // Allow passing positional parameters inside the config object
8786 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
8787 config
= fieldWidget
;
8788 fieldWidget
= config
.fieldWidget
;
8791 // Make sure we have required constructor arguments
8792 if ( fieldWidget
=== undefined ) {
8793 throw new Error( 'Widget not found' );
8796 hasInputWidget
= fieldWidget
.constructor.static.supportsSimpleLabel
;
8798 // Configuration initialization
8799 config
= $.extend( { align
: 'left' }, config
);
8801 // Parent constructor
8802 OO
.ui
.FieldLayout
.parent
.call( this, config
);
8804 // Mixin constructors
8805 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8806 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
8809 this.fieldWidget
= fieldWidget
;
8810 this.errors
= config
.errors
|| [];
8811 this.notices
= config
.notices
|| [];
8812 this.$field
= $( '<div>' );
8813 this.$messages
= $( '<ul>' );
8814 this.$body
= $( '<' + ( hasInputWidget
? 'label' : 'div' ) + '>' );
8816 if ( config
.help
) {
8817 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
8818 classes
: [ 'oo-ui-fieldLayout-help' ],
8824 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
8825 div
.html( config
.help
.toString() );
8827 div
.text( config
.help
);
8829 this.popupButtonWidget
.getPopup().$body
.append(
8830 div
.addClass( 'oo-ui-fieldLayout-help-content' )
8832 this.$help
= this.popupButtonWidget
.$element
;
8834 this.$help
= $( [] );
8838 if ( hasInputWidget
) {
8839 this.$label
.on( 'click', this.onLabelClick
.bind( this ) );
8841 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
8845 .addClass( 'oo-ui-fieldLayout' )
8846 .append( this.$help
, this.$body
);
8847 if ( this.errors
.length
|| this.notices
.length
) {
8848 this.$element
.append( this.$messages
);
8850 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
8851 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
8853 .addClass( 'oo-ui-fieldLayout-field' )
8854 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget
.isDisabled() )
8855 .append( this.fieldWidget
.$element
);
8857 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
8858 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
8860 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
8861 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
8864 this.setAlignment( config
.align
);
8869 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
8870 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
8871 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
8876 * Handle field disable events.
8879 * @param {boolean} value Field is disabled
8881 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
8882 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
8886 * Handle label mouse click events.
8889 * @param {jQuery.Event} e Mouse click event
8891 OO
.ui
.FieldLayout
.prototype.onLabelClick = function () {
8892 this.fieldWidget
.simulateLabelClick();
8897 * Get the widget contained by the field.
8899 * @return {OO.ui.Widget} Field widget
8901 OO
.ui
.FieldLayout
.prototype.getField = function () {
8902 return this.fieldWidget
;
8906 * @param {string} kind 'error' or 'notice'
8907 * @param {string|OO.ui.HtmlSnippet} text
8910 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
8911 var $listItem
, $icon
, message
;
8912 $listItem
= $( '<li>' );
8913 if ( kind
=== 'error' ) {
8914 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
8915 } else if ( kind
=== 'notice' ) {
8916 $icon
= new OO
.ui
.IconWidget( { icon
: 'info' } ).$element
;
8920 message
= new OO
.ui
.LabelWidget( { label
: text
} );
8922 .append( $icon
, message
.$element
)
8923 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
8928 * Set the field alignment mode.
8931 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
8934 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
8935 if ( value
!== this.align
) {
8936 // Default to 'left'
8937 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
8941 if ( value
=== 'inline' ) {
8942 this.$body
.append( this.$field
, this.$label
);
8944 this.$body
.append( this.$label
, this.$field
);
8946 // Set classes. The following classes can be used here:
8947 // * oo-ui-fieldLayout-align-left
8948 // * oo-ui-fieldLayout-align-right
8949 // * oo-ui-fieldLayout-align-top
8950 // * oo-ui-fieldLayout-align-inline
8952 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
8954 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
8962 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
8963 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
8964 * is required and is specified before any optional configuration settings.
8966 * Labels can be aligned in one of four ways:
8968 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8969 * A left-alignment is used for forms with many fields.
8970 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8971 * A right-alignment is used for long but familiar forms which users tab through,
8972 * verifying the current field with a quick glance at the label.
8973 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8974 * that users fill out from top to bottom.
8975 * - **inline**: The label is placed after the field-widget and aligned to the left.
8976 * An inline-alignment is best used with checkboxes or radio buttons.
8978 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
8979 * text is specified.
8982 * // Example of an ActionFieldLayout
8983 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
8984 * new OO.ui.TextInputWidget( {
8985 * placeholder: 'Field widget'
8987 * new OO.ui.ButtonWidget( {
8991 * label: 'An ActionFieldLayout. This label is aligned top',
8993 * help: 'This is help text'
8997 * $( 'body' ).append( actionFieldLayout.$element );
9001 * @extends OO.ui.FieldLayout
9004 * @param {OO.ui.Widget} fieldWidget Field widget
9005 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
9007 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
9008 // Allow passing positional parameters inside the config object
9009 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
9010 config
= fieldWidget
;
9011 fieldWidget
= config
.fieldWidget
;
9012 buttonWidget
= config
.buttonWidget
;
9015 // Parent constructor
9016 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
9019 this.buttonWidget
= buttonWidget
;
9020 this.$button
= $( '<div>' );
9021 this.$input
= $( '<div>' );
9025 .addClass( 'oo-ui-actionFieldLayout' );
9027 .addClass( 'oo-ui-actionFieldLayout-button' )
9028 .append( this.buttonWidget
.$element
);
9030 .addClass( 'oo-ui-actionFieldLayout-input' )
9031 .append( this.fieldWidget
.$element
);
9033 .append( this.$input
, this.$button
);
9038 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
9041 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
9042 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
9043 * configured with a label as well. For more information and examples,
9044 * please see the [OOjs UI documentation on MediaWiki][1].
9047 * // Example of a fieldset layout
9048 * var input1 = new OO.ui.TextInputWidget( {
9049 * placeholder: 'A text input field'
9052 * var input2 = new OO.ui.TextInputWidget( {
9053 * placeholder: 'A text input field'
9056 * var fieldset = new OO.ui.FieldsetLayout( {
9057 * label: 'Example of a fieldset layout'
9060 * fieldset.addItems( [
9061 * new OO.ui.FieldLayout( input1, {
9062 * label: 'Field One'
9064 * new OO.ui.FieldLayout( input2, {
9065 * label: 'Field Two'
9068 * $( 'body' ).append( fieldset.$element );
9070 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9073 * @extends OO.ui.Layout
9074 * @mixins OO.ui.mixin.IconElement
9075 * @mixins OO.ui.mixin.LabelElement
9076 * @mixins OO.ui.mixin.GroupElement
9079 * @param {Object} [config] Configuration options
9080 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
9082 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
9083 // Configuration initialization
9084 config
= config
|| {};
9086 // Parent constructor
9087 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
9089 // Mixin constructors
9090 OO
.ui
.mixin
.IconElement
.call( this, config
);
9091 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9092 OO
.ui
.mixin
.GroupElement
.call( this, config
);
9094 if ( config
.help
) {
9095 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
9096 classes
: [ 'oo-ui-fieldsetLayout-help' ],
9101 this.popupButtonWidget
.getPopup().$body
.append(
9103 .text( config
.help
)
9104 .addClass( 'oo-ui-fieldsetLayout-help-content' )
9106 this.$help
= this.popupButtonWidget
.$element
;
9108 this.$help
= $( [] );
9113 .addClass( 'oo-ui-fieldsetLayout' )
9114 .prepend( this.$help
, this.$icon
, this.$label
, this.$group
);
9115 if ( Array
.isArray( config
.items
) ) {
9116 this.addItems( config
.items
);
9122 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
9123 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
9124 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
9125 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
9128 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
9129 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
9130 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
9131 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9133 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
9134 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
9135 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
9136 * some fancier controls. Some controls have both regular and InputWidget variants, for example
9137 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
9138 * often have simplified APIs to match the capabilities of HTML forms.
9139 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
9141 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
9142 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9145 * // Example of a form layout that wraps a fieldset layout
9146 * var input1 = new OO.ui.TextInputWidget( {
9147 * placeholder: 'Username'
9149 * var input2 = new OO.ui.TextInputWidget( {
9150 * placeholder: 'Password',
9153 * var submit = new OO.ui.ButtonInputWidget( {
9157 * var fieldset = new OO.ui.FieldsetLayout( {
9158 * label: 'A form layout'
9160 * fieldset.addItems( [
9161 * new OO.ui.FieldLayout( input1, {
9162 * label: 'Username',
9165 * new OO.ui.FieldLayout( input2, {
9166 * label: 'Password',
9169 * new OO.ui.FieldLayout( submit )
9171 * var form = new OO.ui.FormLayout( {
9172 * items: [ fieldset ],
9173 * action: '/api/formhandler',
9176 * $( 'body' ).append( form.$element );
9179 * @extends OO.ui.Layout
9180 * @mixins OO.ui.mixin.GroupElement
9183 * @param {Object} [config] Configuration options
9184 * @cfg {string} [method] HTML form `method` attribute
9185 * @cfg {string} [action] HTML form `action` attribute
9186 * @cfg {string} [enctype] HTML form `enctype` attribute
9187 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
9189 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
9190 // Configuration initialization
9191 config
= config
|| {};
9193 // Parent constructor
9194 OO
.ui
.FormLayout
.parent
.call( this, config
);
9196 // Mixin constructors
9197 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
9200 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
9202 // Make sure the action is safe
9203 if ( config
.action
!== undefined && !OO
.ui
.isSafeUrl( config
.action
) ) {
9204 throw new Error( 'Potentially unsafe action provided: ' + config
.action
);
9209 .addClass( 'oo-ui-formLayout' )
9211 method
: config
.method
,
9212 action
: config
.action
,
9213 enctype
: config
.enctype
9215 if ( Array
.isArray( config
.items
) ) {
9216 this.addItems( config
.items
);
9222 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
9223 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
9228 * A 'submit' event is emitted when the form is submitted.
9233 /* Static Properties */
9235 OO
.ui
.FormLayout
.static.tagName
= 'form';
9240 * Handle form submit events.
9243 * @param {jQuery.Event} e Submit event
9246 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
9247 if ( this.emit( 'submit' ) ) {
9253 * 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)
9254 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
9257 * var menuLayout = new OO.ui.MenuLayout( {
9260 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9261 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9262 * select = new OO.ui.SelectWidget( {
9264 * new OO.ui.OptionWidget( {
9268 * new OO.ui.OptionWidget( {
9272 * new OO.ui.OptionWidget( {
9276 * new OO.ui.OptionWidget( {
9281 * } ).on( 'select', function ( item ) {
9282 * menuLayout.setMenuPosition( item.getData() );
9285 * menuLayout.$menu.append(
9286 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
9288 * menuLayout.$content.append(
9289 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
9291 * $( 'body' ).append( menuLayout.$element );
9293 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
9294 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
9295 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
9298 * .oo-ui-menuLayout-menu {
9302 * .oo-ui-menuLayout-content {
9310 * @extends OO.ui.Layout
9313 * @param {Object} [config] Configuration options
9314 * @cfg {boolean} [showMenu=true] Show menu
9315 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
9317 OO
.ui
.MenuLayout
= function OoUiMenuLayout( config
) {
9318 // Configuration initialization
9319 config
= $.extend( {
9321 menuPosition
: 'before'
9324 // Parent constructor
9325 OO
.ui
.MenuLayout
.parent
.call( this, config
);
9330 * @property {jQuery}
9332 this.$menu
= $( '<div>' );
9336 * @property {jQuery}
9338 this.$content
= $( '<div>' );
9342 .addClass( 'oo-ui-menuLayout-menu' );
9343 this.$content
.addClass( 'oo-ui-menuLayout-content' );
9345 .addClass( 'oo-ui-menuLayout' )
9346 .append( this.$content
, this.$menu
);
9347 this.setMenuPosition( config
.menuPosition
);
9348 this.toggleMenu( config
.showMenu
);
9353 OO
.inheritClass( OO
.ui
.MenuLayout
, OO
.ui
.Layout
);
9360 * @param {boolean} showMenu Show menu, omit to toggle
9363 OO
.ui
.MenuLayout
.prototype.toggleMenu = function ( showMenu
) {
9364 showMenu
= showMenu
=== undefined ? !this.showMenu
: !!showMenu
;
9366 if ( this.showMenu
!== showMenu
) {
9367 this.showMenu
= showMenu
;
9369 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu
)
9370 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu
);
9377 * Check if menu is visible
9379 * @return {boolean} Menu is visible
9381 OO
.ui
.MenuLayout
.prototype.isMenuVisible = function () {
9382 return this.showMenu
;
9386 * Set menu position.
9388 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
9389 * @throws {Error} If position value is not supported
9392 OO
.ui
.MenuLayout
.prototype.setMenuPosition = function ( position
) {
9393 this.$element
.removeClass( 'oo-ui-menuLayout-' + this.menuPosition
);
9394 this.menuPosition
= position
;
9395 this.$element
.addClass( 'oo-ui-menuLayout-' + position
);
9401 * Get menu position.
9403 * @return {string} Menu position
9405 OO
.ui
.MenuLayout
.prototype.getMenuPosition = function () {
9406 return this.menuPosition
;
9410 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
9411 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
9412 * through the pages and select which one to display. By default, only one page is
9413 * displayed at a time and the outline is hidden. When a user navigates to a new page,
9414 * the booklet layout automatically focuses on the first focusable element, unless the
9415 * default setting is changed. Optionally, booklets can be configured to show
9416 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
9419 * // Example of a BookletLayout that contains two PageLayouts.
9421 * function PageOneLayout( name, config ) {
9422 * PageOneLayout.parent.call( this, name, config );
9423 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
9425 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
9426 * PageOneLayout.prototype.setupOutlineItem = function () {
9427 * this.outlineItem.setLabel( 'Page One' );
9430 * function PageTwoLayout( name, config ) {
9431 * PageTwoLayout.parent.call( this, name, config );
9432 * this.$element.append( '<p>Second page</p>' );
9434 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
9435 * PageTwoLayout.prototype.setupOutlineItem = function () {
9436 * this.outlineItem.setLabel( 'Page Two' );
9439 * var page1 = new PageOneLayout( 'one' ),
9440 * page2 = new PageTwoLayout( 'two' );
9442 * var booklet = new OO.ui.BookletLayout( {
9446 * booklet.addPages ( [ page1, page2 ] );
9447 * $( 'body' ).append( booklet.$element );
9450 * @extends OO.ui.MenuLayout
9453 * @param {Object} [config] Configuration options
9454 * @cfg {boolean} [continuous=false] Show all pages, one after another
9455 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
9456 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
9457 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
9459 OO
.ui
.BookletLayout
= function OoUiBookletLayout( config
) {
9460 // Configuration initialization
9461 config
= config
|| {};
9463 // Parent constructor
9464 OO
.ui
.BookletLayout
.parent
.call( this, config
);
9467 this.currentPageName
= null;
9469 this.ignoreFocus
= false;
9470 this.stackLayout
= new OO
.ui
.StackLayout( { continuous
: !!config
.continuous
} );
9471 this.$content
.append( this.stackLayout
.$element
);
9472 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
9473 this.outlineVisible
= false;
9474 this.outlined
= !!config
.outlined
;
9475 if ( this.outlined
) {
9476 this.editable
= !!config
.editable
;
9477 this.outlineControlsWidget
= null;
9478 this.outlineSelectWidget
= new OO
.ui
.OutlineSelectWidget();
9479 this.outlinePanel
= new OO
.ui
.PanelLayout( { scrollable
: true } );
9480 this.$menu
.append( this.outlinePanel
.$element
);
9481 this.outlineVisible
= true;
9482 if ( this.editable
) {
9483 this.outlineControlsWidget
= new OO
.ui
.OutlineControlsWidget(
9484 this.outlineSelectWidget
9488 this.toggleMenu( this.outlined
);
9491 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
9492 if ( this.outlined
) {
9493 this.outlineSelectWidget
.connect( this, { select
: 'onOutlineSelectWidgetSelect' } );
9495 if ( this.autoFocus
) {
9496 // Event 'focus' does not bubble, but 'focusin' does
9497 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
9501 this.$element
.addClass( 'oo-ui-bookletLayout' );
9502 this.stackLayout
.$element
.addClass( 'oo-ui-bookletLayout-stackLayout' );
9503 if ( this.outlined
) {
9504 this.outlinePanel
.$element
9505 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
9506 .append( this.outlineSelectWidget
.$element
);
9507 if ( this.editable
) {
9508 this.outlinePanel
.$element
9509 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
9510 .append( this.outlineControlsWidget
.$element
);
9517 OO
.inheritClass( OO
.ui
.BookletLayout
, OO
.ui
.MenuLayout
);
9522 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
9524 * @param {OO.ui.PageLayout} page Current page
9528 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
9531 * @param {OO.ui.PageLayout[]} page Added pages
9532 * @param {number} index Index pages were added at
9536 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
9537 * {@link #removePages removed} from the booklet.
9540 * @param {OO.ui.PageLayout[]} pages Removed pages
9546 * Handle stack layout focus.
9549 * @param {jQuery.Event} e Focusin event
9551 OO
.ui
.BookletLayout
.prototype.onStackLayoutFocus = function ( e
) {
9554 // Find the page that an element was focused within
9555 $target
= $( e
.target
).closest( '.oo-ui-pageLayout' );
9556 for ( name
in this.pages
) {
9557 // Check for page match, exclude current page to find only page changes
9558 if ( this.pages
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentPageName
) {
9559 this.setPage( name
);
9566 * Handle stack layout set events.
9569 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
9571 OO
.ui
.BookletLayout
.prototype.onStackLayoutSet = function ( page
) {
9574 page
.scrollElementIntoView( { complete: function () {
9575 if ( layout
.autoFocus
) {
9583 * Focus the first input in the current page.
9585 * If no page is selected, the first selectable page will be selected.
9586 * If the focus is already in an element on the current page, nothing will happen.
9587 * @param {number} [itemIndex] A specific item to focus on
9589 OO
.ui
.BookletLayout
.prototype.focus = function ( itemIndex
) {
9591 items
= this.stackLayout
.getItems();
9593 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
9594 page
= items
[ itemIndex
];
9596 page
= this.stackLayout
.getCurrentItem();
9599 if ( !page
&& this.outlined
) {
9600 this.selectFirstSelectablePage();
9601 page
= this.stackLayout
.getCurrentItem();
9606 // Only change the focus if is not already in the current page
9607 if ( !page
.$element
.find( ':focus' ).length
) {
9608 $input
= page
.$element
.find( ':input:first' );
9609 if ( $input
.length
) {
9610 $input
[ 0 ].focus();
9616 * Find the first focusable input in the booklet layout and focus
9619 OO
.ui
.BookletLayout
.prototype.focusFirstFocusable = function () {
9622 items
= this.stackLayout
.getItems(),
9623 checkAndFocus = function () {
9624 if ( OO
.ui
.isFocusableElement( $( this ) ) ) {
9631 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
9635 // Find all potentially focusable elements in the item
9636 // and check if they are focusable
9638 .find( 'input, select, textarea, button, object' )
9639 /* jshint loopfunc:true */
9640 .each( checkAndFocus
);
9645 * Handle outline widget select events.
9648 * @param {OO.ui.OptionWidget|null} item Selected item
9650 OO
.ui
.BookletLayout
.prototype.onOutlineSelectWidgetSelect = function ( item
) {
9652 this.setPage( item
.getData() );
9657 * Check if booklet has an outline.
9659 * @return {boolean} Booklet has an outline
9661 OO
.ui
.BookletLayout
.prototype.isOutlined = function () {
9662 return this.outlined
;
9666 * Check if booklet has editing controls.
9668 * @return {boolean} Booklet is editable
9670 OO
.ui
.BookletLayout
.prototype.isEditable = function () {
9671 return this.editable
;
9675 * Check if booklet has a visible outline.
9677 * @return {boolean} Outline is visible
9679 OO
.ui
.BookletLayout
.prototype.isOutlineVisible = function () {
9680 return this.outlined
&& this.outlineVisible
;
9684 * Hide or show the outline.
9686 * @param {boolean} [show] Show outline, omit to invert current state
9689 OO
.ui
.BookletLayout
.prototype.toggleOutline = function ( show
) {
9690 if ( this.outlined
) {
9691 show
= show
=== undefined ? !this.outlineVisible
: !!show
;
9692 this.outlineVisible
= show
;
9693 this.toggleMenu( show
);
9700 * Get the page closest to the specified page.
9702 * @param {OO.ui.PageLayout} page Page to use as a reference point
9703 * @return {OO.ui.PageLayout|null} Page closest to the specified page
9705 OO
.ui
.BookletLayout
.prototype.getClosestPage = function ( page
) {
9706 var next
, prev
, level
,
9707 pages
= this.stackLayout
.getItems(),
9708 index
= pages
.indexOf( page
);
9710 if ( index
!== -1 ) {
9711 next
= pages
[ index
+ 1 ];
9712 prev
= pages
[ index
- 1 ];
9713 // Prefer adjacent pages at the same level
9714 if ( this.outlined
) {
9715 level
= this.outlineSelectWidget
.getItemFromData( page
.getName() ).getLevel();
9718 level
=== this.outlineSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
9724 level
=== this.outlineSelectWidget
.getItemFromData( next
.getName() ).getLevel()
9730 return prev
|| next
|| null;
9734 * Get the outline widget.
9736 * If the booklet is not outlined, the method will return `null`.
9738 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
9740 OO
.ui
.BookletLayout
.prototype.getOutline = function () {
9741 return this.outlineSelectWidget
;
9745 * Get the outline controls widget.
9747 * If the outline is not editable, the method will return `null`.
9749 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
9751 OO
.ui
.BookletLayout
.prototype.getOutlineControls = function () {
9752 return this.outlineControlsWidget
;
9756 * Get a page by its symbolic name.
9758 * @param {string} name Symbolic name of page
9759 * @return {OO.ui.PageLayout|undefined} Page, if found
9761 OO
.ui
.BookletLayout
.prototype.getPage = function ( name
) {
9762 return this.pages
[ name
];
9766 * Get the current page.
9768 * @return {OO.ui.PageLayout|undefined} Current page, if found
9770 OO
.ui
.BookletLayout
.prototype.getCurrentPage = function () {
9771 var name
= this.getCurrentPageName();
9772 return name
? this.getPage( name
) : undefined;
9776 * Get the symbolic name of the current page.
9778 * @return {string|null} Symbolic name of the current page
9780 OO
.ui
.BookletLayout
.prototype.getCurrentPageName = function () {
9781 return this.currentPageName
;
9785 * Add pages to the booklet layout
9787 * When pages are added with the same names as existing pages, the existing pages will be
9788 * automatically removed before the new pages are added.
9790 * @param {OO.ui.PageLayout[]} pages Pages to add
9791 * @param {number} index Index of the insertion point
9795 OO
.ui
.BookletLayout
.prototype.addPages = function ( pages
, index
) {
9796 var i
, len
, name
, page
, item
, currentIndex
,
9797 stackLayoutPages
= this.stackLayout
.getItems(),
9801 // Remove pages with same names
9802 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9804 name
= page
.getName();
9806 if ( Object
.prototype.hasOwnProperty
.call( this.pages
, name
) ) {
9807 // Correct the insertion index
9808 currentIndex
= stackLayoutPages
.indexOf( this.pages
[ name
] );
9809 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
9812 remove
.push( this.pages
[ name
] );
9815 if ( remove
.length
) {
9816 this.removePages( remove
);
9820 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9822 name
= page
.getName();
9823 this.pages
[ page
.getName() ] = page
;
9824 if ( this.outlined
) {
9825 item
= new OO
.ui
.OutlineOptionWidget( { data
: name
} );
9826 page
.setOutlineItem( item
);
9831 if ( this.outlined
&& items
.length
) {
9832 this.outlineSelectWidget
.addItems( items
, index
);
9833 this.selectFirstSelectablePage();
9835 this.stackLayout
.addItems( pages
, index
);
9836 this.emit( 'add', pages
, index
);
9842 * Remove the specified pages from the booklet layout.
9844 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
9846 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
9850 OO
.ui
.BookletLayout
.prototype.removePages = function ( pages
) {
9851 var i
, len
, name
, page
,
9854 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9856 name
= page
.getName();
9857 delete this.pages
[ name
];
9858 if ( this.outlined
) {
9859 items
.push( this.outlineSelectWidget
.getItemFromData( name
) );
9860 page
.setOutlineItem( null );
9863 if ( this.outlined
&& items
.length
) {
9864 this.outlineSelectWidget
.removeItems( items
);
9865 this.selectFirstSelectablePage();
9867 this.stackLayout
.removeItems( pages
);
9868 this.emit( 'remove', pages
);
9874 * Clear all pages from the booklet layout.
9876 * To remove only a subset of pages from the booklet, use the #removePages method.
9881 OO
.ui
.BookletLayout
.prototype.clearPages = function () {
9883 pages
= this.stackLayout
.getItems();
9886 this.currentPageName
= null;
9887 if ( this.outlined
) {
9888 this.outlineSelectWidget
.clearItems();
9889 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9890 pages
[ i
].setOutlineItem( null );
9893 this.stackLayout
.clearItems();
9895 this.emit( 'remove', pages
);
9901 * Set the current page by symbolic name.
9904 * @param {string} name Symbolic name of page
9906 OO
.ui
.BookletLayout
.prototype.setPage = function ( name
) {
9909 page
= this.pages
[ name
];
9911 if ( name
!== this.currentPageName
) {
9912 if ( this.outlined
) {
9913 selectedItem
= this.outlineSelectWidget
.getSelectedItem();
9914 if ( selectedItem
&& selectedItem
.getData() !== name
) {
9915 this.outlineSelectWidget
.selectItemByData( name
);
9919 if ( this.currentPageName
&& this.pages
[ this.currentPageName
] ) {
9920 this.pages
[ this.currentPageName
].setActive( false );
9921 // Blur anything focused if the next page doesn't have anything focusable - this
9922 // is not needed if the next page has something focusable because once it is focused
9923 // this blur happens automatically
9924 if ( this.autoFocus
&& !page
.$element
.find( ':input' ).length
) {
9925 $focused
= this.pages
[ this.currentPageName
].$element
.find( ':focus' );
9926 if ( $focused
.length
) {
9927 $focused
[ 0 ].blur();
9931 this.currentPageName
= name
;
9932 this.stackLayout
.setItem( page
);
9933 page
.setActive( true );
9934 this.emit( 'set', page
);
9940 * Select the first selectable page.
9944 OO
.ui
.BookletLayout
.prototype.selectFirstSelectablePage = function () {
9945 if ( !this.outlineSelectWidget
.getSelectedItem() ) {
9946 this.outlineSelectWidget
.selectItem( this.outlineSelectWidget
.getFirstSelectableItem() );
9953 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
9954 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
9955 * select which one to display. By default, only one card is displayed at a time. When a user
9956 * navigates to a new card, the index layout automatically focuses on the first focusable element,
9957 * unless the default setting is changed.
9959 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
9962 * // Example of a IndexLayout that contains two CardLayouts.
9964 * function CardOneLayout( name, config ) {
9965 * CardOneLayout.parent.call( this, name, config );
9966 * this.$element.append( '<p>First card</p>' );
9968 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
9969 * CardOneLayout.prototype.setupTabItem = function () {
9970 * this.tabItem.setLabel( 'Card One' );
9973 * function CardTwoLayout( name, config ) {
9974 * CardTwoLayout.parent.call( this, name, config );
9975 * this.$element.append( '<p>Second card</p>' );
9977 * OO.inheritClass( CardTwoLayout, OO.ui.CardLayout );
9978 * CardTwoLayout.prototype.setupTabItem = function () {
9979 * this.tabItem.setLabel( 'Card Two' );
9982 * var card1 = new CardOneLayout( 'one' ),
9983 * card2 = new CardTwoLayout( 'two' );
9985 * var index = new OO.ui.IndexLayout();
9987 * index.addCards ( [ card1, card2 ] );
9988 * $( 'body' ).append( index.$element );
9991 * @extends OO.ui.MenuLayout
9994 * @param {Object} [config] Configuration options
9995 * @cfg {boolean} [continuous=false] Show all cards, one after another
9996 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
9998 OO
.ui
.IndexLayout
= function OoUiIndexLayout( config
) {
9999 // Configuration initialization
10000 config
= $.extend( {}, config
, { menuPosition
: 'top' } );
10002 // Parent constructor
10003 OO
.ui
.IndexLayout
.parent
.call( this, config
);
10006 this.currentCardName
= null;
10008 this.ignoreFocus
= false;
10009 this.stackLayout
= new OO
.ui
.StackLayout( { continuous
: !!config
.continuous
} );
10010 this.$content
.append( this.stackLayout
.$element
);
10011 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
10013 this.tabSelectWidget
= new OO
.ui
.TabSelectWidget();
10014 this.tabPanel
= new OO
.ui
.PanelLayout();
10015 this.$menu
.append( this.tabPanel
.$element
);
10017 this.toggleMenu( true );
10020 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
10021 this.tabSelectWidget
.connect( this, { select
: 'onTabSelectWidgetSelect' } );
10022 if ( this.autoFocus
) {
10023 // Event 'focus' does not bubble, but 'focusin' does
10024 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
10028 this.$element
.addClass( 'oo-ui-indexLayout' );
10029 this.stackLayout
.$element
.addClass( 'oo-ui-indexLayout-stackLayout' );
10030 this.tabPanel
.$element
10031 .addClass( 'oo-ui-indexLayout-tabPanel' )
10032 .append( this.tabSelectWidget
.$element
);
10037 OO
.inheritClass( OO
.ui
.IndexLayout
, OO
.ui
.MenuLayout
);
10042 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
10044 * @param {OO.ui.CardLayout} card Current card
10048 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
10051 * @param {OO.ui.CardLayout[]} card Added cards
10052 * @param {number} index Index cards were added at
10056 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
10057 * {@link #removeCards removed} from the index.
10060 * @param {OO.ui.CardLayout[]} cards Removed cards
10066 * Handle stack layout focus.
10069 * @param {jQuery.Event} e Focusin event
10071 OO
.ui
.IndexLayout
.prototype.onStackLayoutFocus = function ( e
) {
10074 // Find the card that an element was focused within
10075 $target
= $( e
.target
).closest( '.oo-ui-cardLayout' );
10076 for ( name
in this.cards
) {
10077 // Check for card match, exclude current card to find only card changes
10078 if ( this.cards
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentCardName
) {
10079 this.setCard( name
);
10086 * Handle stack layout set events.
10089 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
10091 OO
.ui
.IndexLayout
.prototype.onStackLayoutSet = function ( card
) {
10094 card
.scrollElementIntoView( { complete: function () {
10095 if ( layout
.autoFocus
) {
10103 * Focus the first input in the current card.
10105 * If no card is selected, the first selectable card will be selected.
10106 * If the focus is already in an element on the current card, nothing will happen.
10107 * @param {number} [itemIndex] A specific item to focus on
10109 OO
.ui
.IndexLayout
.prototype.focus = function ( itemIndex
) {
10111 items
= this.stackLayout
.getItems();
10113 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
10114 card
= items
[ itemIndex
];
10116 card
= this.stackLayout
.getCurrentItem();
10120 this.selectFirstSelectableCard();
10121 card
= this.stackLayout
.getCurrentItem();
10126 // Only change the focus if is not already in the current card
10127 if ( !card
.$element
.find( ':focus' ).length
) {
10128 $input
= card
.$element
.find( ':input:first' );
10129 if ( $input
.length
) {
10130 $input
[ 0 ].focus();
10136 * Find the first focusable input in the index layout and focus
10139 OO
.ui
.IndexLayout
.prototype.focusFirstFocusable = function () {
10142 items
= this.stackLayout
.getItems(),
10143 checkAndFocus = function () {
10144 if ( OO
.ui
.isFocusableElement( $( this ) ) ) {
10151 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
10155 // Find all potentially focusable elements in the item
10156 // and check if they are focusable
10157 items
[ i
].$element
10158 .find( 'input, select, textarea, button, object' )
10159 .each( checkAndFocus
);
10164 * Handle tab widget select events.
10167 * @param {OO.ui.OptionWidget|null} item Selected item
10169 OO
.ui
.IndexLayout
.prototype.onTabSelectWidgetSelect = function ( item
) {
10171 this.setCard( item
.getData() );
10176 * Get the card closest to the specified card.
10178 * @param {OO.ui.CardLayout} card Card to use as a reference point
10179 * @return {OO.ui.CardLayout|null} Card closest to the specified card
10181 OO
.ui
.IndexLayout
.prototype.getClosestCard = function ( card
) {
10182 var next
, prev
, level
,
10183 cards
= this.stackLayout
.getItems(),
10184 index
= cards
.indexOf( card
);
10186 if ( index
!== -1 ) {
10187 next
= cards
[ index
+ 1 ];
10188 prev
= cards
[ index
- 1 ];
10189 // Prefer adjacent cards at the same level
10190 level
= this.tabSelectWidget
.getItemFromData( card
.getName() ).getLevel();
10193 level
=== this.tabSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
10199 level
=== this.tabSelectWidget
.getItemFromData( next
.getName() ).getLevel()
10204 return prev
|| next
|| null;
10208 * Get the tabs widget.
10210 * @return {OO.ui.TabSelectWidget} Tabs widget
10212 OO
.ui
.IndexLayout
.prototype.getTabs = function () {
10213 return this.tabSelectWidget
;
10217 * Get a card by its symbolic name.
10219 * @param {string} name Symbolic name of card
10220 * @return {OO.ui.CardLayout|undefined} Card, if found
10222 OO
.ui
.IndexLayout
.prototype.getCard = function ( name
) {
10223 return this.cards
[ name
];
10227 * Get the current card.
10229 * @return {OO.ui.CardLayout|undefined} Current card, if found
10231 OO
.ui
.IndexLayout
.prototype.getCurrentCard = function () {
10232 var name
= this.getCurrentCardName();
10233 return name
? this.getCard( name
) : undefined;
10237 * Get the symbolic name of the current card.
10239 * @return {string|null} Symbolic name of the current card
10241 OO
.ui
.IndexLayout
.prototype.getCurrentCardName = function () {
10242 return this.currentCardName
;
10246 * Add cards to the index layout
10248 * When cards are added with the same names as existing cards, the existing cards will be
10249 * automatically removed before the new cards are added.
10251 * @param {OO.ui.CardLayout[]} cards Cards to add
10252 * @param {number} index Index of the insertion point
10256 OO
.ui
.IndexLayout
.prototype.addCards = function ( cards
, index
) {
10257 var i
, len
, name
, card
, item
, currentIndex
,
10258 stackLayoutCards
= this.stackLayout
.getItems(),
10262 // Remove cards with same names
10263 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10265 name
= card
.getName();
10267 if ( Object
.prototype.hasOwnProperty
.call( this.cards
, name
) ) {
10268 // Correct the insertion index
10269 currentIndex
= stackLayoutCards
.indexOf( this.cards
[ name
] );
10270 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
10273 remove
.push( this.cards
[ name
] );
10276 if ( remove
.length
) {
10277 this.removeCards( remove
);
10281 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10283 name
= card
.getName();
10284 this.cards
[ card
.getName() ] = card
;
10285 item
= new OO
.ui
.TabOptionWidget( { data
: name
} );
10286 card
.setTabItem( item
);
10287 items
.push( item
);
10290 if ( items
.length
) {
10291 this.tabSelectWidget
.addItems( items
, index
);
10292 this.selectFirstSelectableCard();
10294 this.stackLayout
.addItems( cards
, index
);
10295 this.emit( 'add', cards
, index
);
10301 * Remove the specified cards from the index layout.
10303 * To remove all cards from the index, you may wish to use the #clearCards method instead.
10305 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
10309 OO
.ui
.IndexLayout
.prototype.removeCards = function ( cards
) {
10310 var i
, len
, name
, card
,
10313 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10315 name
= card
.getName();
10316 delete this.cards
[ name
];
10317 items
.push( this.tabSelectWidget
.getItemFromData( name
) );
10318 card
.setTabItem( null );
10320 if ( items
.length
) {
10321 this.tabSelectWidget
.removeItems( items
);
10322 this.selectFirstSelectableCard();
10324 this.stackLayout
.removeItems( cards
);
10325 this.emit( 'remove', cards
);
10331 * Clear all cards from the index layout.
10333 * To remove only a subset of cards from the index, use the #removeCards method.
10338 OO
.ui
.IndexLayout
.prototype.clearCards = function () {
10340 cards
= this.stackLayout
.getItems();
10343 this.currentCardName
= null;
10344 this.tabSelectWidget
.clearItems();
10345 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10346 cards
[ i
].setTabItem( null );
10348 this.stackLayout
.clearItems();
10350 this.emit( 'remove', cards
);
10356 * Set the current card by symbolic name.
10359 * @param {string} name Symbolic name of card
10361 OO
.ui
.IndexLayout
.prototype.setCard = function ( name
) {
10364 card
= this.cards
[ name
];
10366 if ( name
!== this.currentCardName
) {
10367 selectedItem
= this.tabSelectWidget
.getSelectedItem();
10368 if ( selectedItem
&& selectedItem
.getData() !== name
) {
10369 this.tabSelectWidget
.selectItemByData( name
);
10372 if ( this.currentCardName
&& this.cards
[ this.currentCardName
] ) {
10373 this.cards
[ this.currentCardName
].setActive( false );
10374 // Blur anything focused if the next card doesn't have anything focusable - this
10375 // is not needed if the next card has something focusable because once it is focused
10376 // this blur happens automatically
10377 if ( this.autoFocus
&& !card
.$element
.find( ':input' ).length
) {
10378 $focused
= this.cards
[ this.currentCardName
].$element
.find( ':focus' );
10379 if ( $focused
.length
) {
10380 $focused
[ 0 ].blur();
10384 this.currentCardName
= name
;
10385 this.stackLayout
.setItem( card
);
10386 card
.setActive( true );
10387 this.emit( 'set', card
);
10393 * Select the first selectable card.
10397 OO
.ui
.IndexLayout
.prototype.selectFirstSelectableCard = function () {
10398 if ( !this.tabSelectWidget
.getSelectedItem() ) {
10399 this.tabSelectWidget
.selectItem( this.tabSelectWidget
.getFirstSelectableItem() );
10406 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10407 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10410 * // Example of a panel layout
10411 * var panel = new OO.ui.PanelLayout( {
10415 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10417 * $( 'body' ).append( panel.$element );
10420 * @extends OO.ui.Layout
10423 * @param {Object} [config] Configuration options
10424 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10425 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10426 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10427 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10429 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
10430 // Configuration initialization
10431 config
= $.extend( {
10438 // Parent constructor
10439 OO
.ui
.PanelLayout
.parent
.call( this, config
);
10442 this.$element
.addClass( 'oo-ui-panelLayout' );
10443 if ( config
.scrollable
) {
10444 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
10446 if ( config
.padded
) {
10447 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
10449 if ( config
.expanded
) {
10450 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
10452 if ( config
.framed
) {
10453 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
10459 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
10462 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
10463 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
10464 * rather extended to include the required content and functionality.
10466 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
10467 * item is customized (with a label) using the #setupTabItem method. See
10468 * {@link OO.ui.IndexLayout IndexLayout} for an example.
10471 * @extends OO.ui.PanelLayout
10474 * @param {string} name Unique symbolic name of card
10475 * @param {Object} [config] Configuration options
10477 OO
.ui
.CardLayout
= function OoUiCardLayout( name
, config
) {
10478 // Allow passing positional parameters inside the config object
10479 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
10481 name
= config
.name
;
10484 // Configuration initialization
10485 config
= $.extend( { scrollable
: true }, config
);
10487 // Parent constructor
10488 OO
.ui
.CardLayout
.parent
.call( this, config
);
10492 this.tabItem
= null;
10493 this.active
= false;
10496 this.$element
.addClass( 'oo-ui-cardLayout' );
10501 OO
.inheritClass( OO
.ui
.CardLayout
, OO
.ui
.PanelLayout
);
10506 * An 'active' event is emitted when the card becomes active. Cards become active when they are
10507 * shown in a index layout that is configured to display only one card at a time.
10510 * @param {boolean} active Card is active
10516 * Get the symbolic name of the card.
10518 * @return {string} Symbolic name of card
10520 OO
.ui
.CardLayout
.prototype.getName = function () {
10525 * Check if card is active.
10527 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
10528 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
10530 * @return {boolean} Card is active
10532 OO
.ui
.CardLayout
.prototype.isActive = function () {
10533 return this.active
;
10539 * The tab item allows users to access the card from the index's tab
10540 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
10542 * @return {OO.ui.TabOptionWidget|null} Tab option widget
10544 OO
.ui
.CardLayout
.prototype.getTabItem = function () {
10545 return this.tabItem
;
10549 * Set or unset the tab item.
10551 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
10552 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
10553 * level), use #setupTabItem instead of this method.
10555 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
10558 OO
.ui
.CardLayout
.prototype.setTabItem = function ( tabItem
) {
10559 this.tabItem
= tabItem
|| null;
10561 this.setupTabItem();
10567 * Set up the tab item.
10569 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
10570 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
10571 * the #setTabItem method instead.
10573 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
10576 OO
.ui
.CardLayout
.prototype.setupTabItem = function () {
10581 * Set the card to its 'active' state.
10583 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
10584 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
10585 * context, setting the active state on a card does nothing.
10587 * @param {boolean} value Card is active
10590 OO
.ui
.CardLayout
.prototype.setActive = function ( active
) {
10593 if ( active
!== this.active
) {
10594 this.active
= active
;
10595 this.$element
.toggleClass( 'oo-ui-cardLayout-active', this.active
);
10596 this.emit( 'active', this.active
);
10601 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
10602 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
10603 * rather extended to include the required content and functionality.
10605 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
10606 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
10607 * {@link OO.ui.BookletLayout BookletLayout} for an example.
10610 * @extends OO.ui.PanelLayout
10613 * @param {string} name Unique symbolic name of page
10614 * @param {Object} [config] Configuration options
10616 OO
.ui
.PageLayout
= function OoUiPageLayout( name
, config
) {
10617 // Allow passing positional parameters inside the config object
10618 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
10620 name
= config
.name
;
10623 // Configuration initialization
10624 config
= $.extend( { scrollable
: true }, config
);
10626 // Parent constructor
10627 OO
.ui
.PageLayout
.parent
.call( this, config
);
10631 this.outlineItem
= null;
10632 this.active
= false;
10635 this.$element
.addClass( 'oo-ui-pageLayout' );
10640 OO
.inheritClass( OO
.ui
.PageLayout
, OO
.ui
.PanelLayout
);
10645 * An 'active' event is emitted when the page becomes active. Pages become active when they are
10646 * shown in a booklet layout that is configured to display only one page at a time.
10649 * @param {boolean} active Page is active
10655 * Get the symbolic name of the page.
10657 * @return {string} Symbolic name of page
10659 OO
.ui
.PageLayout
.prototype.getName = function () {
10664 * Check if page is active.
10666 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
10667 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
10669 * @return {boolean} Page is active
10671 OO
.ui
.PageLayout
.prototype.isActive = function () {
10672 return this.active
;
10676 * Get outline item.
10678 * The outline item allows users to access the page from the booklet's outline
10679 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
10681 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
10683 OO
.ui
.PageLayout
.prototype.getOutlineItem = function () {
10684 return this.outlineItem
;
10688 * Set or unset the outline item.
10690 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
10691 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
10692 * level), use #setupOutlineItem instead of this method.
10694 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
10697 OO
.ui
.PageLayout
.prototype.setOutlineItem = function ( outlineItem
) {
10698 this.outlineItem
= outlineItem
|| null;
10699 if ( outlineItem
) {
10700 this.setupOutlineItem();
10706 * Set up the outline item.
10708 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
10709 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
10710 * the #setOutlineItem method instead.
10712 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
10715 OO
.ui
.PageLayout
.prototype.setupOutlineItem = function () {
10720 * Set the page to its 'active' state.
10722 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
10723 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
10724 * context, setting the active state on a page does nothing.
10726 * @param {boolean} value Page is active
10729 OO
.ui
.PageLayout
.prototype.setActive = function ( active
) {
10732 if ( active
!== this.active
) {
10733 this.active
= active
;
10734 this.$element
.toggleClass( 'oo-ui-pageLayout-active', active
);
10735 this.emit( 'active', this.active
);
10740 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
10741 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
10742 * by setting the #continuous option to 'true'.
10745 * // A stack layout with two panels, configured to be displayed continously
10746 * var myStack = new OO.ui.StackLayout( {
10748 * new OO.ui.PanelLayout( {
10749 * $content: $( '<p>Panel One</p>' ),
10753 * new OO.ui.PanelLayout( {
10754 * $content: $( '<p>Panel Two</p>' ),
10761 * $( 'body' ).append( myStack.$element );
10764 * @extends OO.ui.PanelLayout
10765 * @mixins OO.ui.mixin.GroupElement
10768 * @param {Object} [config] Configuration options
10769 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
10770 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
10772 OO
.ui
.StackLayout
= function OoUiStackLayout( config
) {
10773 // Configuration initialization
10774 config
= $.extend( { scrollable
: true }, config
);
10776 // Parent constructor
10777 OO
.ui
.StackLayout
.parent
.call( this, config
);
10779 // Mixin constructors
10780 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
10783 this.currentItem
= null;
10784 this.continuous
= !!config
.continuous
;
10787 this.$element
.addClass( 'oo-ui-stackLayout' );
10788 if ( this.continuous
) {
10789 this.$element
.addClass( 'oo-ui-stackLayout-continuous' );
10791 if ( Array
.isArray( config
.items
) ) {
10792 this.addItems( config
.items
);
10798 OO
.inheritClass( OO
.ui
.StackLayout
, OO
.ui
.PanelLayout
);
10799 OO
.mixinClass( OO
.ui
.StackLayout
, OO
.ui
.mixin
.GroupElement
);
10804 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
10805 * {@link #clearItems cleared} or {@link #setItem displayed}.
10808 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
10814 * Get the current panel.
10816 * @return {OO.ui.Layout|null}
10818 OO
.ui
.StackLayout
.prototype.getCurrentItem = function () {
10819 return this.currentItem
;
10823 * Unset the current item.
10826 * @param {OO.ui.StackLayout} layout
10829 OO
.ui
.StackLayout
.prototype.unsetCurrentItem = function () {
10830 var prevItem
= this.currentItem
;
10831 if ( prevItem
=== null ) {
10835 this.currentItem
= null;
10836 this.emit( 'set', null );
10840 * Add panel layouts to the stack layout.
10842 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
10843 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
10846 * @param {OO.ui.Layout[]} items Panels to add
10847 * @param {number} [index] Index of the insertion point
10850 OO
.ui
.StackLayout
.prototype.addItems = function ( items
, index
) {
10851 // Update the visibility
10852 this.updateHiddenState( items
, this.currentItem
);
10855 OO
.ui
.mixin
.GroupElement
.prototype.addItems
.call( this, items
, index
);
10857 if ( !this.currentItem
&& items
.length
) {
10858 this.setItem( items
[ 0 ] );
10865 * Remove the specified panels from the stack layout.
10867 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
10868 * you may wish to use the #clearItems method instead.
10870 * @param {OO.ui.Layout[]} items Panels to remove
10874 OO
.ui
.StackLayout
.prototype.removeItems = function ( items
) {
10876 OO
.ui
.mixin
.GroupElement
.prototype.removeItems
.call( this, items
);
10878 if ( items
.indexOf( this.currentItem
) !== -1 ) {
10879 if ( this.items
.length
) {
10880 this.setItem( this.items
[ 0 ] );
10882 this.unsetCurrentItem();
10890 * Clear all panels from the stack layout.
10892 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
10893 * a subset of panels, use the #removeItems method.
10898 OO
.ui
.StackLayout
.prototype.clearItems = function () {
10899 this.unsetCurrentItem();
10900 OO
.ui
.mixin
.GroupElement
.prototype.clearItems
.call( this );
10906 * Show the specified panel.
10908 * If another panel is currently displayed, it will be hidden.
10910 * @param {OO.ui.Layout} item Panel to show
10914 OO
.ui
.StackLayout
.prototype.setItem = function ( item
) {
10915 if ( item
!== this.currentItem
) {
10916 this.updateHiddenState( this.items
, item
);
10918 if ( this.items
.indexOf( item
) !== -1 ) {
10919 this.currentItem
= item
;
10920 this.emit( 'set', item
);
10922 this.unsetCurrentItem();
10930 * Update the visibility of all items in case of non-continuous view.
10932 * Ensure all items are hidden except for the selected one.
10933 * This method does nothing when the stack is continuous.
10936 * @param {OO.ui.Layout[]} items Item list iterate over
10937 * @param {OO.ui.Layout} [selectedItem] Selected item to show
10939 OO
.ui
.StackLayout
.prototype.updateHiddenState = function ( items
, selectedItem
) {
10942 if ( !this.continuous
) {
10943 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
10944 if ( !selectedItem
|| selectedItem
!== items
[ i
] ) {
10945 items
[ i
].$element
.addClass( 'oo-ui-element-hidden' );
10948 if ( selectedItem
) {
10949 selectedItem
.$element
.removeClass( 'oo-ui-element-hidden' );
10955 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
10956 * items), with small margins between them. Convenient when you need to put a number of block-level
10957 * widgets on a single line next to each other.
10959 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
10962 * // HorizontalLayout with a text input and a label
10963 * var layout = new OO.ui.HorizontalLayout( {
10965 * new OO.ui.LabelWidget( { label: 'Label' } ),
10966 * new OO.ui.TextInputWidget( { value: 'Text' } )
10969 * $( 'body' ).append( layout.$element );
10972 * @extends OO.ui.Layout
10973 * @mixins OO.ui.mixin.GroupElement
10976 * @param {Object} [config] Configuration options
10977 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
10979 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
10980 // Configuration initialization
10981 config
= config
|| {};
10983 // Parent constructor
10984 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
10986 // Mixin constructors
10987 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
10990 this.$element
.addClass( 'oo-ui-horizontalLayout' );
10991 if ( Array
.isArray( config
.items
) ) {
10992 this.addItems( config
.items
);
10998 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
10999 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);
11002 * BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11003 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11004 * and {@link OO.ui.ListToolGroup ListToolGroup}). The {@link OO.ui.Tool tools} in a BarToolGroup are
11005 * displayed by icon in a single row. The title of the tool is displayed when users move the mouse over
11008 * BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar is
11012 * // Example of a BarToolGroup with two tools
11013 * var toolFactory = new OO.ui.ToolFactory();
11014 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11015 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11017 * // We will be placing status text in this element when tools are used
11018 * var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' );
11020 * // Define the tools that we're going to place in our toolbar
11022 * // Create a class inheriting from OO.ui.Tool
11023 * function PictureTool() {
11024 * PictureTool.parent.apply( this, arguments );
11026 * OO.inheritClass( PictureTool, OO.ui.Tool );
11027 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
11028 * // of 'icon' and 'title' (displayed icon and text).
11029 * PictureTool.static.name = 'picture';
11030 * PictureTool.static.icon = 'picture';
11031 * PictureTool.static.title = 'Insert picture';
11032 * // Defines the action that will happen when this tool is selected (clicked).
11033 * PictureTool.prototype.onSelect = function () {
11034 * $area.text( 'Picture tool clicked!' );
11035 * // Never display this tool as "active" (selected).
11036 * this.setActive( false );
11038 * // Make this tool available in our toolFactory and thus our toolbar
11039 * toolFactory.register( PictureTool );
11041 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
11042 * // little popup window (a PopupWidget).
11043 * function HelpTool( toolGroup, config ) {
11044 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11049 * this.popup.$body.append( '<p>I am helpful!</p>' );
11051 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11052 * HelpTool.static.name = 'help';
11053 * HelpTool.static.icon = 'help';
11054 * HelpTool.static.title = 'Help';
11055 * toolFactory.register( HelpTool );
11057 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11058 * // used once (but not all defined tools must be used).
11061 * // 'bar' tool groups display tools by icon only
11063 * include: [ 'picture', 'help' ]
11067 * // Create some UI around the toolbar and place it in the document
11068 * var frame = new OO.ui.PanelLayout( {
11072 * var contentFrame = new OO.ui.PanelLayout( {
11076 * frame.$element.append(
11077 * toolbar.$element,
11078 * contentFrame.$element.append( $area )
11080 * $( 'body' ).append( frame.$element );
11082 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11084 * toolbar.initialize();
11086 * For more information about how to add tools to a bar tool group, please see {@link OO.ui.ToolGroup toolgroup}.
11087 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11089 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11092 * @extends OO.ui.ToolGroup
11095 * @param {OO.ui.Toolbar} toolbar
11096 * @param {Object} [config] Configuration options
11098 OO
.ui
.BarToolGroup
= function OoUiBarToolGroup( toolbar
, config
) {
11099 // Allow passing positional parameters inside the config object
11100 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11102 toolbar
= config
.toolbar
;
11105 // Parent constructor
11106 OO
.ui
.BarToolGroup
.parent
.call( this, toolbar
, config
);
11109 this.$element
.addClass( 'oo-ui-barToolGroup' );
11114 OO
.inheritClass( OO
.ui
.BarToolGroup
, OO
.ui
.ToolGroup
);
11116 /* Static Properties */
11118 OO
.ui
.BarToolGroup
.static.titleTooltips
= true;
11120 OO
.ui
.BarToolGroup
.static.accelTooltips
= true;
11122 OO
.ui
.BarToolGroup
.static.name
= 'bar';
11125 * PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup}
11126 * and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup--an overlaid menu or list of tools with an
11127 * optional icon and label. This class can be used for other base classes that also use this functionality.
11131 * @extends OO.ui.ToolGroup
11132 * @mixins OO.ui.mixin.IconElement
11133 * @mixins OO.ui.mixin.IndicatorElement
11134 * @mixins OO.ui.mixin.LabelElement
11135 * @mixins OO.ui.mixin.TitledElement
11136 * @mixins OO.ui.mixin.ClippableElement
11137 * @mixins OO.ui.mixin.TabIndexedElement
11140 * @param {OO.ui.Toolbar} toolbar
11141 * @param {Object} [config] Configuration options
11142 * @cfg {string} [header] Text to display at the top of the popup
11144 OO
.ui
.PopupToolGroup
= function OoUiPopupToolGroup( toolbar
, config
) {
11145 // Allow passing positional parameters inside the config object
11146 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11148 toolbar
= config
.toolbar
;
11151 // Configuration initialization
11152 config
= config
|| {};
11154 // Parent constructor
11155 OO
.ui
.PopupToolGroup
.parent
.call( this, toolbar
, config
);
11158 this.active
= false;
11159 this.dragging
= false;
11160 this.onBlurHandler
= this.onBlur
.bind( this );
11161 this.$handle
= $( '<span>' );
11163 // Mixin constructors
11164 OO
.ui
.mixin
.IconElement
.call( this, config
);
11165 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
11166 OO
.ui
.mixin
.LabelElement
.call( this, config
);
11167 OO
.ui
.mixin
.TitledElement
.call( this, config
);
11168 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
11169 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
11173 keydown
: this.onHandleMouseKeyDown
.bind( this ),
11174 keyup
: this.onHandleMouseKeyUp
.bind( this ),
11175 mousedown
: this.onHandleMouseKeyDown
.bind( this ),
11176 mouseup
: this.onHandleMouseKeyUp
.bind( this )
11181 .addClass( 'oo-ui-popupToolGroup-handle' )
11182 .append( this.$icon
, this.$label
, this.$indicator
);
11183 // If the pop-up should have a header, add it to the top of the toolGroup.
11184 // Note: If this feature is useful for other widgets, we could abstract it into an
11185 // OO.ui.HeaderedElement mixin constructor.
11186 if ( config
.header
!== undefined ) {
11188 .prepend( $( '<span>' )
11189 .addClass( 'oo-ui-popupToolGroup-header' )
11190 .text( config
.header
)
11194 .addClass( 'oo-ui-popupToolGroup' )
11195 .prepend( this.$handle
);
11200 OO
.inheritClass( OO
.ui
.PopupToolGroup
, OO
.ui
.ToolGroup
);
11201 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.IconElement
);
11202 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.IndicatorElement
);
11203 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.LabelElement
);
11204 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.TitledElement
);
11205 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.ClippableElement
);
11206 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.TabIndexedElement
);
11213 OO
.ui
.PopupToolGroup
.prototype.setDisabled = function () {
11215 OO
.ui
.PopupToolGroup
.parent
.prototype.setDisabled
.apply( this, arguments
);
11217 if ( this.isDisabled() && this.isElementAttached() ) {
11218 this.setActive( false );
11223 * Handle focus being lost.
11225 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
11228 * @param {jQuery.Event} e Mouse up or key up event
11230 OO
.ui
.PopupToolGroup
.prototype.onBlur = function ( e
) {
11231 // Only deactivate when clicking outside the dropdown element
11232 if ( $( e
.target
).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element
[ 0 ] ) {
11233 this.setActive( false );
11240 OO
.ui
.PopupToolGroup
.prototype.onMouseKeyUp = function ( e
) {
11241 // Only close toolgroup when a tool was actually selected
11243 !this.isDisabled() && this.pressed
&& this.pressed
=== this.getTargetTool( e
) &&
11244 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11246 this.setActive( false );
11248 return OO
.ui
.PopupToolGroup
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11252 * Handle mouse up and key up events.
11255 * @param {jQuery.Event} e Mouse up or key up event
11257 OO
.ui
.PopupToolGroup
.prototype.onHandleMouseKeyUp = function ( e
) {
11259 !this.isDisabled() &&
11260 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11267 * Handle mouse down and key down events.
11270 * @param {jQuery.Event} e Mouse down or key down event
11272 OO
.ui
.PopupToolGroup
.prototype.onHandleMouseKeyDown = function ( e
) {
11274 !this.isDisabled() &&
11275 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11277 this.setActive( !this.active
);
11283 * Switch into 'active' mode.
11285 * When active, the popup is visible. A mouseup event anywhere in the document will trigger
11288 OO
.ui
.PopupToolGroup
.prototype.setActive = function ( value
) {
11289 var containerWidth
, containerLeft
;
11291 if ( this.active
!== value
) {
11292 this.active
= value
;
11294 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler
);
11295 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler
);
11297 this.$clippable
.css( 'left', '' );
11298 // Try anchoring the popup to the left first
11299 this.$element
.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
11300 this.toggleClipping( true );
11301 if ( this.isClippedHorizontally() ) {
11302 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
11303 this.toggleClipping( false );
11305 .removeClass( 'oo-ui-popupToolGroup-left' )
11306 .addClass( 'oo-ui-popupToolGroup-right' );
11307 this.toggleClipping( true );
11309 if ( this.isClippedHorizontally() ) {
11310 // Anchoring to the right also caused the popup to clip, so just make it fill the container
11311 containerWidth
= this.$clippableContainer
.width();
11312 containerLeft
= this.$clippableContainer
.offset().left
;
11314 this.toggleClipping( false );
11315 this.$element
.removeClass( 'oo-ui-popupToolGroup-right' );
11317 this.$clippable
.css( {
11318 left
: -( this.$element
.offset().left
- containerLeft
),
11319 width
: containerWidth
11323 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler
);
11324 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler
);
11325 this.$element
.removeClass(
11326 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
11328 this.toggleClipping( false );
11334 * ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11335 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11336 * and {@link OO.ui.BarToolGroup BarToolGroup}). The {@link OO.ui.Tool tools} in a ListToolGroup are displayed
11337 * by label in a dropdown menu. The title of the tool is used as the label text. The menu itself can be configured
11338 * with a label, icon, indicator, header, and title.
11340 * ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a ‘More’ option that
11341 * users can select to see the full list of tools. If a collapsed toolgroup is expanded, a ‘Fewer’ option permits
11342 * users to collapse the list again.
11344 * ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the toolbar is set up. The factory
11345 * requires the ListToolGroup's symbolic name, 'list', which is specified along with the other configurations. For more
11346 * information about how to add tools to a ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11349 * // Example of a ListToolGroup
11350 * var toolFactory = new OO.ui.ToolFactory();
11351 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11352 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11354 * // Configure and register two tools
11355 * function SettingsTool() {
11356 * SettingsTool.parent.apply( this, arguments );
11358 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11359 * SettingsTool.static.name = 'settings';
11360 * SettingsTool.static.icon = 'settings';
11361 * SettingsTool.static.title = 'Change settings';
11362 * SettingsTool.prototype.onSelect = function () {
11363 * this.setActive( false );
11365 * toolFactory.register( SettingsTool );
11366 * // Register two more tools, nothing interesting here
11367 * function StuffTool() {
11368 * StuffTool.parent.apply( this, arguments );
11370 * OO.inheritClass( StuffTool, OO.ui.Tool );
11371 * StuffTool.static.name = 'stuff';
11372 * StuffTool.static.icon = 'ellipsis';
11373 * StuffTool.static.title = 'Change the world';
11374 * StuffTool.prototype.onSelect = function () {
11375 * this.setActive( false );
11377 * toolFactory.register( StuffTool );
11380 * // Configurations for list toolgroup.
11382 * label: 'ListToolGroup',
11383 * indicator: 'down',
11385 * title: 'This is the title, displayed when user moves the mouse over the list toolgroup',
11386 * header: 'This is the header',
11387 * include: [ 'settings', 'stuff' ],
11388 * allowCollapse: ['stuff']
11392 * // Create some UI around the toolbar and place it in the document
11393 * var frame = new OO.ui.PanelLayout( {
11397 * frame.$element.append(
11400 * $( 'body' ).append( frame.$element );
11401 * // Build the toolbar. This must be done after the toolbar has been appended to the document.
11402 * toolbar.initialize();
11404 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11406 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11409 * @extends OO.ui.PopupToolGroup
11412 * @param {OO.ui.Toolbar} toolbar
11413 * @param {Object} [config] Configuration options
11414 * @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible tools
11415 * will only be displayed if users click the ‘More’ option displayed at the bottom of the list. If
11416 * the list is expanded, a ‘Fewer’ option permits users to collapse the list again. Any tools that
11417 * are included in the toolgroup, but are not designated as collapsible, will always be displayed.
11418 * To open a collapsible list in its expanded state, set #expanded to 'true'.
11419 * @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as collapsible.
11420 * Unless #expanded is set to true, the collapsible tools will be collapsed when the list is first opened.
11421 * @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools have
11422 * been designated as collapsible. When expanded is set to true, all tools in the group will be displayed
11423 * when the list is first opened. Users can collapse the list with a ‘Fewer’ option at the bottom.
11425 OO
.ui
.ListToolGroup
= function OoUiListToolGroup( toolbar
, config
) {
11426 // Allow passing positional parameters inside the config object
11427 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11429 toolbar
= config
.toolbar
;
11432 // Configuration initialization
11433 config
= config
|| {};
11435 // Properties (must be set before parent constructor, which calls #populate)
11436 this.allowCollapse
= config
.allowCollapse
;
11437 this.forceExpand
= config
.forceExpand
;
11438 this.expanded
= config
.expanded
!== undefined ? config
.expanded
: false;
11439 this.collapsibleTools
= [];
11441 // Parent constructor
11442 OO
.ui
.ListToolGroup
.parent
.call( this, toolbar
, config
);
11445 this.$element
.addClass( 'oo-ui-listToolGroup' );
11450 OO
.inheritClass( OO
.ui
.ListToolGroup
, OO
.ui
.PopupToolGroup
);
11452 /* Static Properties */
11454 OO
.ui
.ListToolGroup
.static.name
= 'list';
11461 OO
.ui
.ListToolGroup
.prototype.populate = function () {
11462 var i
, len
, allowCollapse
= [];
11464 OO
.ui
.ListToolGroup
.parent
.prototype.populate
.call( this );
11466 // Update the list of collapsible tools
11467 if ( this.allowCollapse
!== undefined ) {
11468 allowCollapse
= this.allowCollapse
;
11469 } else if ( this.forceExpand
!== undefined ) {
11470 allowCollapse
= OO
.simpleArrayDifference( Object
.keys( this.tools
), this.forceExpand
);
11473 this.collapsibleTools
= [];
11474 for ( i
= 0, len
= allowCollapse
.length
; i
< len
; i
++ ) {
11475 if ( this.tools
[ allowCollapse
[ i
] ] !== undefined ) {
11476 this.collapsibleTools
.push( this.tools
[ allowCollapse
[ i
] ] );
11480 // Keep at the end, even when tools are added
11481 this.$group
.append( this.getExpandCollapseTool().$element
);
11483 this.getExpandCollapseTool().toggle( this.collapsibleTools
.length
!== 0 );
11484 this.updateCollapsibleState();
11487 OO
.ui
.ListToolGroup
.prototype.getExpandCollapseTool = function () {
11488 var ExpandCollapseTool
;
11489 if ( this.expandCollapseTool
=== undefined ) {
11490 ExpandCollapseTool = function () {
11491 ExpandCollapseTool
.parent
.apply( this, arguments
);
11494 OO
.inheritClass( ExpandCollapseTool
, OO
.ui
.Tool
);
11496 ExpandCollapseTool
.prototype.onSelect = function () {
11497 this.toolGroup
.expanded
= !this.toolGroup
.expanded
;
11498 this.toolGroup
.updateCollapsibleState();
11499 this.setActive( false );
11501 ExpandCollapseTool
.prototype.onUpdateState = function () {
11502 // Do nothing. Tool interface requires an implementation of this function.
11505 ExpandCollapseTool
.static.name
= 'more-fewer';
11507 this.expandCollapseTool
= new ExpandCollapseTool( this );
11509 return this.expandCollapseTool
;
11515 OO
.ui
.ListToolGroup
.prototype.onMouseKeyUp = function ( e
) {
11516 // Do not close the popup when the user wants to show more/fewer tools
11518 $( e
.target
).closest( '.oo-ui-tool-name-more-fewer' ).length
&&
11519 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11521 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
11522 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
11523 return OO
.ui
.ListToolGroup
.parent
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11525 return OO
.ui
.ListToolGroup
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11529 OO
.ui
.ListToolGroup
.prototype.updateCollapsibleState = function () {
11532 this.getExpandCollapseTool()
11533 .setIcon( this.expanded
? 'collapse' : 'expand' )
11534 .setTitle( OO
.ui
.msg( this.expanded
? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
11536 for ( i
= 0, len
= this.collapsibleTools
.length
; i
< len
; i
++ ) {
11537 this.collapsibleTools
[ i
].toggle( this.expanded
);
11542 * MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11543 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.BarToolGroup BarToolGroup}
11544 * and {@link OO.ui.ListToolGroup ListToolGroup}). MenuToolGroups contain selectable {@link OO.ui.Tool tools},
11545 * which are displayed by label in a dropdown menu. The tool's title is used as the label text, and the
11546 * menu label is updated to reflect which tool or tools are currently selected. If no tools are selected,
11547 * the menu label is empty. The menu can be configured with an indicator, icon, title, and/or header.
11549 * MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar
11550 * is set up. Note that all tools must define an {@link OO.ui.Tool#onUpdateState onUpdateState} method if
11551 * a MenuToolGroup is used.
11554 * // Example of a MenuToolGroup
11555 * var toolFactory = new OO.ui.ToolFactory();
11556 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11557 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11559 * // We will be placing status text in this element when tools are used
11560 * var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the dropdown menu.' );
11562 * // Define the tools that we're going to place in our toolbar
11564 * function SettingsTool() {
11565 * SettingsTool.parent.apply( this, arguments );
11566 * this.reallyActive = false;
11568 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11569 * SettingsTool.static.name = 'settings';
11570 * SettingsTool.static.icon = 'settings';
11571 * SettingsTool.static.title = 'Change settings';
11572 * SettingsTool.prototype.onSelect = function () {
11573 * $area.text( 'Settings tool clicked!' );
11574 * // Toggle the active state on each click
11575 * this.reallyActive = !this.reallyActive;
11576 * this.setActive( this.reallyActive );
11577 * // To update the menu label
11578 * this.toolbar.emit( 'updateState' );
11580 * SettingsTool.prototype.onUpdateState = function () {
11582 * toolFactory.register( SettingsTool );
11584 * function StuffTool() {
11585 * StuffTool.parent.apply( this, arguments );
11586 * this.reallyActive = false;
11588 * OO.inheritClass( StuffTool, OO.ui.Tool );
11589 * StuffTool.static.name = 'stuff';
11590 * StuffTool.static.icon = 'ellipsis';
11591 * StuffTool.static.title = 'More stuff';
11592 * StuffTool.prototype.onSelect = function () {
11593 * $area.text( 'More stuff tool clicked!' );
11594 * // Toggle the active state on each click
11595 * this.reallyActive = !this.reallyActive;
11596 * this.setActive( this.reallyActive );
11597 * // To update the menu label
11598 * this.toolbar.emit( 'updateState' );
11600 * StuffTool.prototype.onUpdateState = function () {
11602 * toolFactory.register( StuffTool );
11604 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11605 * // used once (but not all defined tools must be used).
11609 * header: 'This is the (optional) header',
11610 * title: 'This is the (optional) title',
11611 * indicator: 'down',
11612 * include: [ 'settings', 'stuff' ]
11616 * // Create some UI around the toolbar and place it in the document
11617 * var frame = new OO.ui.PanelLayout( {
11621 * var contentFrame = new OO.ui.PanelLayout( {
11625 * frame.$element.append(
11626 * toolbar.$element,
11627 * contentFrame.$element.append( $area )
11629 * $( 'body' ).append( frame.$element );
11631 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11633 * toolbar.initialize();
11634 * toolbar.emit( 'updateState' );
11636 * For more information about how to add tools to a MenuToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11637 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki] [1].
11639 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11642 * @extends OO.ui.PopupToolGroup
11645 * @param {OO.ui.Toolbar} toolbar
11646 * @param {Object} [config] Configuration options
11648 OO
.ui
.MenuToolGroup
= function OoUiMenuToolGroup( toolbar
, config
) {
11649 // Allow passing positional parameters inside the config object
11650 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11652 toolbar
= config
.toolbar
;
11655 // Configuration initialization
11656 config
= config
|| {};
11658 // Parent constructor
11659 OO
.ui
.MenuToolGroup
.parent
.call( this, toolbar
, config
);
11662 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
11665 this.$element
.addClass( 'oo-ui-menuToolGroup' );
11670 OO
.inheritClass( OO
.ui
.MenuToolGroup
, OO
.ui
.PopupToolGroup
);
11672 /* Static Properties */
11674 OO
.ui
.MenuToolGroup
.static.name
= 'menu';
11679 * Handle the toolbar state being updated.
11681 * When the state changes, the title of each active item in the menu will be joined together and
11682 * used as a label for the group. The label will be empty if none of the items are active.
11686 OO
.ui
.MenuToolGroup
.prototype.onUpdateState = function () {
11690 for ( name
in this.tools
) {
11691 if ( this.tools
[ name
].isActive() ) {
11692 labelTexts
.push( this.tools
[ name
].getTitle() );
11696 this.setLabel( labelTexts
.join( ', ' ) || ' ' );
11700 * Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. Each popup tool is configured
11701 * 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
11702 * an #onSelect or #onUpdateState method, as these methods have been implemented already.
11704 * // Example of a popup tool. When selected, a popup tool displays
11705 * // a popup window.
11706 * function HelpTool( toolGroup, config ) {
11707 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11712 * this.popup.$body.append( '<p>I am helpful!</p>' );
11714 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11715 * HelpTool.static.name = 'help';
11716 * HelpTool.static.icon = 'help';
11717 * HelpTool.static.title = 'Help';
11718 * toolFactory.register( HelpTool );
11720 * For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. For more information about
11721 * toolbars in genreral, please see the [OOjs UI documentation on MediaWiki][1].
11723 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11727 * @extends OO.ui.Tool
11728 * @mixins OO.ui.mixin.PopupElement
11731 * @param {OO.ui.ToolGroup} toolGroup
11732 * @param {Object} [config] Configuration options
11734 OO
.ui
.PopupTool
= function OoUiPopupTool( toolGroup
, config
) {
11735 // Allow passing positional parameters inside the config object
11736 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
11737 config
= toolGroup
;
11738 toolGroup
= config
.toolGroup
;
11741 // Parent constructor
11742 OO
.ui
.PopupTool
.parent
.call( this, toolGroup
, config
);
11744 // Mixin constructors
11745 OO
.ui
.mixin
.PopupElement
.call( this, config
);
11749 .addClass( 'oo-ui-popupTool' )
11750 .append( this.popup
.$element
);
11755 OO
.inheritClass( OO
.ui
.PopupTool
, OO
.ui
.Tool
);
11756 OO
.mixinClass( OO
.ui
.PopupTool
, OO
.ui
.mixin
.PopupElement
);
11761 * Handle the tool being selected.
11765 OO
.ui
.PopupTool
.prototype.onSelect = function () {
11766 if ( !this.isDisabled() ) {
11767 this.popup
.toggle();
11769 this.setActive( false );
11774 * Handle the toolbar state being updated.
11778 OO
.ui
.PopupTool
.prototype.onUpdateState = function () {
11779 this.setActive( false );
11783 * A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools}
11784 * and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used
11785 * inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from
11786 * the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list}
11787 * when the ToolGroupTool is selected.
11789 * // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', defined elsewhere.
11791 * function SettingsTool() {
11792 * SettingsTool.parent.apply( this, arguments );
11794 * OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool );
11795 * SettingsTool.static.name = 'settings';
11796 * SettingsTool.static.title = 'Change settings';
11797 * SettingsTool.static.groupConfig = {
11798 * icon: 'settings',
11799 * label: 'ToolGroupTool',
11800 * include: [ 'setting1', 'setting2' ]
11802 * toolFactory.register( SettingsTool );
11804 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
11806 * Please note that this implementation is subject to change per [T74159] [2].
11808 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars#ToolGroupTool
11809 * [2]: https://phabricator.wikimedia.org/T74159
11813 * @extends OO.ui.Tool
11816 * @param {OO.ui.ToolGroup} toolGroup
11817 * @param {Object} [config] Configuration options
11819 OO
.ui
.ToolGroupTool
= function OoUiToolGroupTool( toolGroup
, config
) {
11820 // Allow passing positional parameters inside the config object
11821 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
11822 config
= toolGroup
;
11823 toolGroup
= config
.toolGroup
;
11826 // Parent constructor
11827 OO
.ui
.ToolGroupTool
.parent
.call( this, toolGroup
, config
);
11830 this.innerToolGroup
= this.createGroup( this.constructor.static.groupConfig
);
11833 this.innerToolGroup
.connect( this, { disable
: 'onToolGroupDisable' } );
11836 this.$link
.remove();
11838 .addClass( 'oo-ui-toolGroupTool' )
11839 .append( this.innerToolGroup
.$element
);
11844 OO
.inheritClass( OO
.ui
.ToolGroupTool
, OO
.ui
.Tool
);
11846 /* Static Properties */
11849 * Toolgroup configuration.
11851 * The toolgroup configuration consists of the tools to include, as well as an icon and label
11852 * to use for the bar item. Tools can be included by symbolic name, group, or with the
11853 * wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information.
11855 * @property {Object.<string,Array>}
11857 OO
.ui
.ToolGroupTool
.static.groupConfig
= {};
11862 * Handle the tool being selected.
11866 OO
.ui
.ToolGroupTool
.prototype.onSelect = function () {
11867 this.innerToolGroup
.setActive( !this.innerToolGroup
.active
);
11872 * Synchronize disabledness state of the tool with the inner toolgroup.
11875 * @param {boolean} disabled Element is disabled
11877 OO
.ui
.ToolGroupTool
.prototype.onToolGroupDisable = function ( disabled
) {
11878 this.setDisabled( disabled
);
11882 * Handle the toolbar state being updated.
11886 OO
.ui
.ToolGroupTool
.prototype.onUpdateState = function () {
11887 this.setActive( false );
11891 * Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration.
11893 * @param {Object.<string,Array>} group Toolgroup configuration. Please see {@link OO.ui.ToolGroup toolgroup} for
11894 * more information.
11895 * @return {OO.ui.ListToolGroup}
11897 OO
.ui
.ToolGroupTool
.prototype.createGroup = function ( group
) {
11898 if ( group
.include
=== '*' ) {
11899 // Apply defaults to catch-all groups
11900 if ( group
.label
=== undefined ) {
11901 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
11905 return this.toolbar
.getToolGroupFactory().create( 'list', this.toolbar
, group
);
11909 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
11911 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
11916 * @extends OO.ui.mixin.GroupElement
11919 * @param {Object} [config] Configuration options
11921 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
11922 // Parent constructor
11923 OO
.ui
.mixin
.GroupWidget
.parent
.call( this, config
);
11928 OO
.inheritClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
11933 * Set the disabled state of the widget.
11935 * This will also update the disabled state of child widgets.
11937 * @param {boolean} disabled Disable widget
11940 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
11944 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
11945 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
11947 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
11948 if ( this.items
) {
11949 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
11950 this.items
[ i
].updateDisabled();
11958 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
11960 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
11961 * allows bidirectional communication.
11963 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
11971 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
11978 * Check if widget is disabled.
11980 * Checks parent if present, making disabled state inheritable.
11982 * @return {boolean} Widget is disabled
11984 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
11985 return this.disabled
||
11986 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
11990 * Set group element is in.
11992 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
11995 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
11997 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
11998 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
12000 // Initialize item disabled states
12001 this.updateDisabled();
12007 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
12008 * Controls include moving items up and down, removing items, and adding different kinds of items.
12010 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
12013 * @extends OO.ui.Widget
12014 * @mixins OO.ui.mixin.GroupElement
12015 * @mixins OO.ui.mixin.IconElement
12018 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
12019 * @param {Object} [config] Configuration options
12020 * @cfg {Object} [abilities] List of abilties
12021 * @cfg {boolean} [abilities.move=true] Allow moving movable items
12022 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
12024 OO
.ui
.OutlineControlsWidget
= function OoUiOutlineControlsWidget( outline
, config
) {
12025 // Allow passing positional parameters inside the config object
12026 if ( OO
.isPlainObject( outline
) && config
=== undefined ) {
12028 outline
= config
.outline
;
12031 // Configuration initialization
12032 config
= $.extend( { icon
: 'add' }, config
);
12034 // Parent constructor
12035 OO
.ui
.OutlineControlsWidget
.parent
.call( this, config
);
12037 // Mixin constructors
12038 OO
.ui
.mixin
.GroupElement
.call( this, config
);
12039 OO
.ui
.mixin
.IconElement
.call( this, config
);
12042 this.outline
= outline
;
12043 this.$movers
= $( '<div>' );
12044 this.upButton
= new OO
.ui
.ButtonWidget( {
12047 title
: OO
.ui
.msg( 'ooui-outline-control-move-up' )
12049 this.downButton
= new OO
.ui
.ButtonWidget( {
12052 title
: OO
.ui
.msg( 'ooui-outline-control-move-down' )
12054 this.removeButton
= new OO
.ui
.ButtonWidget( {
12057 title
: OO
.ui
.msg( 'ooui-outline-control-remove' )
12059 this.abilities
= { move: true, remove
: true };
12062 outline
.connect( this, {
12063 select
: 'onOutlineChange',
12064 add
: 'onOutlineChange',
12065 remove
: 'onOutlineChange'
12067 this.upButton
.connect( this, { click
: [ 'emit', 'move', -1 ] } );
12068 this.downButton
.connect( this, { click
: [ 'emit', 'move', 1 ] } );
12069 this.removeButton
.connect( this, { click
: [ 'emit', 'remove' ] } );
12072 this.$element
.addClass( 'oo-ui-outlineControlsWidget' );
12073 this.$group
.addClass( 'oo-ui-outlineControlsWidget-items' );
12075 .addClass( 'oo-ui-outlineControlsWidget-movers' )
12076 .append( this.removeButton
.$element
, this.upButton
.$element
, this.downButton
.$element
);
12077 this.$element
.append( this.$icon
, this.$group
, this.$movers
);
12078 this.setAbilities( config
.abilities
|| {} );
12083 OO
.inheritClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.Widget
);
12084 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.mixin
.GroupElement
);
12085 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.mixin
.IconElement
);
12091 * @param {number} places Number of places to move
12103 * @param {Object} abilities List of abilties
12104 * @param {boolean} [abilities.move] Allow moving movable items
12105 * @param {boolean} [abilities.remove] Allow removing removable items
12107 OO
.ui
.OutlineControlsWidget
.prototype.setAbilities = function ( abilities
) {
12110 for ( ability
in this.abilities
) {
12111 if ( abilities
[ ability
] !== undefined ) {
12112 this.abilities
[ ability
] = !!abilities
[ ability
];
12116 this.onOutlineChange();
12122 * Handle outline change events.
12124 OO
.ui
.OutlineControlsWidget
.prototype.onOutlineChange = function () {
12125 var i
, len
, firstMovable
, lastMovable
,
12126 items
= this.outline
.getItems(),
12127 selectedItem
= this.outline
.getSelectedItem(),
12128 movable
= this.abilities
.move && selectedItem
&& selectedItem
.isMovable(),
12129 removable
= this.abilities
.remove
&& selectedItem
&& selectedItem
.isRemovable();
12133 len
= items
.length
;
12134 while ( ++i
< len
) {
12135 if ( items
[ i
].isMovable() ) {
12136 firstMovable
= items
[ i
];
12142 if ( items
[ i
].isMovable() ) {
12143 lastMovable
= items
[ i
];
12148 this.upButton
.setDisabled( !movable
|| selectedItem
=== firstMovable
);
12149 this.downButton
.setDisabled( !movable
|| selectedItem
=== lastMovable
);
12150 this.removeButton
.setDisabled( !removable
);
12154 * ToggleWidget implements basic behavior of widgets with an on/off state.
12155 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
12159 * @extends OO.ui.Widget
12162 * @param {Object} [config] Configuration options
12163 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
12164 * By default, the toggle is in the 'off' state.
12166 OO
.ui
.ToggleWidget
= function OoUiToggleWidget( config
) {
12167 // Configuration initialization
12168 config
= config
|| {};
12170 // Parent constructor
12171 OO
.ui
.ToggleWidget
.parent
.call( this, config
);
12177 this.$element
.addClass( 'oo-ui-toggleWidget' );
12178 this.setValue( !!config
.value
);
12183 OO
.inheritClass( OO
.ui
.ToggleWidget
, OO
.ui
.Widget
);
12190 * A change event is emitted when the on/off state of the toggle changes.
12192 * @param {boolean} value Value representing the new state of the toggle
12198 * Get the value representing the toggle’s state.
12200 * @return {boolean} The on/off state of the toggle
12202 OO
.ui
.ToggleWidget
.prototype.getValue = function () {
12207 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
12209 * @param {boolean} value The state of the toggle
12213 OO
.ui
.ToggleWidget
.prototype.setValue = function ( value
) {
12215 if ( this.value
!== value
) {
12216 this.value
= value
;
12217 this.emit( 'change', value
);
12218 this.$element
.toggleClass( 'oo-ui-toggleWidget-on', value
);
12219 this.$element
.toggleClass( 'oo-ui-toggleWidget-off', !value
);
12220 this.$element
.attr( 'aria-checked', value
.toString() );
12226 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
12227 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
12228 * removed, and cleared from the group.
12231 * // Example: A ButtonGroupWidget with two buttons
12232 * var button1 = new OO.ui.PopupButtonWidget( {
12233 * label: 'Select a category',
12236 * $content: $( '<p>List of categories...</p>' ),
12241 * var button2 = new OO.ui.ButtonWidget( {
12242 * label: 'Add item'
12244 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
12245 * items: [button1, button2]
12247 * $( 'body' ).append( buttonGroup.$element );
12250 * @extends OO.ui.Widget
12251 * @mixins OO.ui.mixin.GroupElement
12254 * @param {Object} [config] Configuration options
12255 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
12257 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
12258 // Configuration initialization
12259 config
= config
|| {};
12261 // Parent constructor
12262 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
12264 // Mixin constructors
12265 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
12268 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
12269 if ( Array
.isArray( config
.items
) ) {
12270 this.addItems( config
.items
);
12276 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
12277 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
12280 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
12281 * feels, and functionality can be customized via the class’s configuration options
12282 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12285 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
12288 * // A button widget
12289 * var button = new OO.ui.ButtonWidget( {
12290 * label: 'Button with Icon',
12292 * iconTitle: 'Remove'
12294 * $( 'body' ).append( button.$element );
12296 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
12299 * @extends OO.ui.Widget
12300 * @mixins OO.ui.mixin.ButtonElement
12301 * @mixins OO.ui.mixin.IconElement
12302 * @mixins OO.ui.mixin.IndicatorElement
12303 * @mixins OO.ui.mixin.LabelElement
12304 * @mixins OO.ui.mixin.TitledElement
12305 * @mixins OO.ui.mixin.FlaggedElement
12306 * @mixins OO.ui.mixin.TabIndexedElement
12307 * @mixins OO.ui.mixin.AccessKeyedElement
12310 * @param {Object} [config] Configuration options
12311 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
12312 * @cfg {string} [target] The frame or window in which to open the hyperlink.
12313 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
12315 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
12316 // Configuration initialization
12317 config
= config
|| {};
12319 // Parent constructor
12320 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
12322 // Mixin constructors
12323 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
12324 OO
.ui
.mixin
.IconElement
.call( this, config
);
12325 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
12326 OO
.ui
.mixin
.LabelElement
.call( this, config
);
12327 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
12328 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
12329 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
12330 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$button
} ) );
12334 this.target
= null;
12335 this.noFollow
= false;
12338 this.connect( this, { disable
: 'onDisable' } );
12341 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
12343 .addClass( 'oo-ui-buttonWidget' )
12344 .append( this.$button
);
12345 this.setHref( config
.href
);
12346 this.setTarget( config
.target
);
12347 this.setNoFollow( config
.noFollow
);
12352 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
12353 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
12354 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
12355 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
12356 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
12357 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
12358 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
12359 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
12360 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
12367 OO
.ui
.ButtonWidget
.prototype.onMouseDown = function ( e
) {
12368 if ( !this.isDisabled() ) {
12369 // Remove the tab-index while the button is down to prevent the button from stealing focus
12370 this.$button
.removeAttr( 'tabindex' );
12373 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown
.call( this, e
);
12379 OO
.ui
.ButtonWidget
.prototype.onMouseUp = function ( e
) {
12380 if ( !this.isDisabled() ) {
12381 // Restore the tab-index after the button is up to restore the button's accessibility
12382 this.$button
.attr( 'tabindex', this.tabIndex
);
12385 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp
.call( this, e
);
12389 * Get hyperlink location.
12391 * @return {string} Hyperlink location
12393 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
12398 * Get hyperlink target.
12400 * @return {string} Hyperlink target
12402 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
12403 return this.target
;
12407 * Get search engine traversal hint.
12409 * @return {boolean} Whether search engines should avoid traversing this hyperlink
12411 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
12412 return this.noFollow
;
12416 * Set hyperlink location.
12418 * @param {string|null} href Hyperlink location, null to remove
12420 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
12421 href
= typeof href
=== 'string' ? href
: null;
12422 if ( href
!== null ) {
12423 if ( !OO
.ui
.isSafeUrl( href
) ) {
12424 throw new Error( 'Potentially unsafe href provided: ' + href
);
12429 if ( href
!== this.href
) {
12438 * Update the `href` attribute, in case of changes to href or
12444 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
12445 if ( this.href
!== null && !this.isDisabled() ) {
12446 this.$button
.attr( 'href', this.href
);
12448 this.$button
.removeAttr( 'href' );
12455 * Handle disable events.
12458 * @param {boolean} disabled Element is disabled
12460 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
12465 * Set hyperlink target.
12467 * @param {string|null} target Hyperlink target, null to remove
12469 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
12470 target
= typeof target
=== 'string' ? target
: null;
12472 if ( target
!== this.target
) {
12473 this.target
= target
;
12474 if ( target
!== null ) {
12475 this.$button
.attr( 'target', target
);
12477 this.$button
.removeAttr( 'target' );
12485 * Set search engine traversal hint.
12487 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
12489 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
12490 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
12492 if ( noFollow
!== this.noFollow
) {
12493 this.noFollow
= noFollow
;
12495 this.$button
.attr( 'rel', 'nofollow' );
12497 this.$button
.removeAttr( 'rel' );
12505 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
12506 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
12509 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
12510 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12513 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
12516 * @extends OO.ui.ButtonWidget
12517 * @mixins OO.ui.mixin.PendingElement
12520 * @param {Object} [config] Configuration options
12521 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12522 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
12523 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
12524 * for more information about setting modes.
12525 * @cfg {boolean} [framed=false] Render the action button with a frame
12527 OO
.ui
.ActionWidget
= function OoUiActionWidget( config
) {
12528 // Configuration initialization
12529 config
= $.extend( { framed
: false }, config
);
12531 // Parent constructor
12532 OO
.ui
.ActionWidget
.parent
.call( this, config
);
12534 // Mixin constructors
12535 OO
.ui
.mixin
.PendingElement
.call( this, config
);
12538 this.action
= config
.action
|| '';
12539 this.modes
= config
.modes
|| [];
12544 this.$element
.addClass( 'oo-ui-actionWidget' );
12549 OO
.inheritClass( OO
.ui
.ActionWidget
, OO
.ui
.ButtonWidget
);
12550 OO
.mixinClass( OO
.ui
.ActionWidget
, OO
.ui
.mixin
.PendingElement
);
12555 * A resize event is emitted when the size of the widget changes.
12563 * Check if the action is configured to be available in the specified `mode`.
12565 * @param {string} mode Name of mode
12566 * @return {boolean} The action is configured with the mode
12568 OO
.ui
.ActionWidget
.prototype.hasMode = function ( mode
) {
12569 return this.modes
.indexOf( mode
) !== -1;
12573 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12577 OO
.ui
.ActionWidget
.prototype.getAction = function () {
12578 return this.action
;
12582 * Get the symbolic name of the mode or modes for which the action is configured to be available.
12584 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
12585 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
12588 * @return {string[]}
12590 OO
.ui
.ActionWidget
.prototype.getModes = function () {
12591 return this.modes
.slice();
12595 * Emit a resize event if the size has changed.
12600 OO
.ui
.ActionWidget
.prototype.propagateResize = function () {
12603 if ( this.isElementAttached() ) {
12604 width
= this.$element
.width();
12605 height
= this.$element
.height();
12607 if ( width
!== this.width
|| height
!== this.height
) {
12608 this.width
= width
;
12609 this.height
= height
;
12610 this.emit( 'resize' );
12620 OO
.ui
.ActionWidget
.prototype.setIcon = function () {
12622 OO
.ui
.mixin
.IconElement
.prototype.setIcon
.apply( this, arguments
);
12623 this.propagateResize();
12631 OO
.ui
.ActionWidget
.prototype.setLabel = function () {
12633 OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.apply( this, arguments
);
12634 this.propagateResize();
12642 OO
.ui
.ActionWidget
.prototype.setFlags = function () {
12644 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags
.apply( this, arguments
);
12645 this.propagateResize();
12653 OO
.ui
.ActionWidget
.prototype.clearFlags = function () {
12655 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags
.apply( this, arguments
);
12656 this.propagateResize();
12662 * Toggle the visibility of the action button.
12664 * @param {boolean} [show] Show button, omit to toggle visibility
12667 OO
.ui
.ActionWidget
.prototype.toggle = function () {
12669 OO
.ui
.ActionWidget
.parent
.prototype.toggle
.apply( this, arguments
);
12670 this.propagateResize();
12676 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
12677 * which is used to display additional information or options.
12680 * // Example of a popup button.
12681 * var popupButton = new OO.ui.PopupButtonWidget( {
12682 * label: 'Popup button with options',
12685 * $content: $( '<p>Additional options here.</p>' ),
12687 * align: 'force-left'
12690 * // Append the button to the DOM.
12691 * $( 'body' ).append( popupButton.$element );
12694 * @extends OO.ui.ButtonWidget
12695 * @mixins OO.ui.mixin.PopupElement
12698 * @param {Object} [config] Configuration options
12700 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
12701 // Parent constructor
12702 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
12704 // Mixin constructors
12705 OO
.ui
.mixin
.PopupElement
.call( this, config
);
12708 this.connect( this, { click
: 'onAction' } );
12712 .addClass( 'oo-ui-popupButtonWidget' )
12713 .attr( 'aria-haspopup', 'true' )
12714 .append( this.popup
.$element
);
12719 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
12720 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
12725 * Handle the button action being triggered.
12729 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
12730 this.popup
.toggle();
12734 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
12735 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
12736 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
12737 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
12738 * and {@link OO.ui.mixin.LabelElement labels}. Please see
12739 * the [OOjs UI documentation][1] on MediaWiki for more information.
12742 * // Toggle buttons in the 'off' and 'on' state.
12743 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
12744 * label: 'Toggle Button off'
12746 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
12747 * label: 'Toggle Button on',
12750 * // Append the buttons to the DOM.
12751 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
12753 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
12756 * @extends OO.ui.ToggleWidget
12757 * @mixins OO.ui.mixin.ButtonElement
12758 * @mixins OO.ui.mixin.IconElement
12759 * @mixins OO.ui.mixin.IndicatorElement
12760 * @mixins OO.ui.mixin.LabelElement
12761 * @mixins OO.ui.mixin.TitledElement
12762 * @mixins OO.ui.mixin.FlaggedElement
12763 * @mixins OO.ui.mixin.TabIndexedElement
12766 * @param {Object} [config] Configuration options
12767 * @cfg {boolean} [value=false] The toggle button’s initial on/off
12768 * state. By default, the button is in the 'off' state.
12770 OO
.ui
.ToggleButtonWidget
= function OoUiToggleButtonWidget( config
) {
12771 // Configuration initialization
12772 config
= config
|| {};
12774 // Parent constructor
12775 OO
.ui
.ToggleButtonWidget
.parent
.call( this, config
);
12777 // Mixin constructors
12778 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
12779 OO
.ui
.mixin
.IconElement
.call( this, config
);
12780 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
12781 OO
.ui
.mixin
.LabelElement
.call( this, config
);
12782 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
12783 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
12784 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
12787 this.connect( this, { click
: 'onAction' } );
12790 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
12792 .addClass( 'oo-ui-toggleButtonWidget' )
12793 .append( this.$button
);
12798 OO
.inheritClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.ToggleWidget
);
12799 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
12800 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.IconElement
);
12801 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
12802 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.LabelElement
);
12803 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.TitledElement
);
12804 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
12805 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
12810 * Handle the button action being triggered.
12814 OO
.ui
.ToggleButtonWidget
.prototype.onAction = function () {
12815 this.setValue( !this.value
);
12821 OO
.ui
.ToggleButtonWidget
.prototype.setValue = function ( value
) {
12823 if ( value
!== this.value
) {
12824 // Might be called from parent constructor before ButtonElement constructor
12825 if ( this.$button
) {
12826 this.$button
.attr( 'aria-pressed', value
.toString() );
12828 this.setActive( value
);
12832 OO
.ui
.ToggleButtonWidget
.parent
.prototype.setValue
.call( this, value
);
12840 OO
.ui
.ToggleButtonWidget
.prototype.setButtonElement = function ( $button
) {
12841 if ( this.$button
) {
12842 this.$button
.removeAttr( 'aria-pressed' );
12844 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement
.call( this, $button
);
12845 this.$button
.attr( 'aria-pressed', this.value
.toString() );
12849 * CapsuleMultiSelectWidgets are something like a {@link OO.ui.ComboBoxWidget combo box widget}
12850 * that allows for selecting multiple values.
12852 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
12855 * // Example: A CapsuleMultiSelectWidget.
12856 * var capsule = new OO.ui.CapsuleMultiSelectWidget( {
12857 * label: 'CapsuleMultiSelectWidget',
12858 * selected: [ 'Option 1', 'Option 3' ],
12861 * new OO.ui.MenuOptionWidget( {
12862 * data: 'Option 1',
12863 * label: 'Option One'
12865 * new OO.ui.MenuOptionWidget( {
12866 * data: 'Option 2',
12867 * label: 'Option Two'
12869 * new OO.ui.MenuOptionWidget( {
12870 * data: 'Option 3',
12871 * label: 'Option Three'
12873 * new OO.ui.MenuOptionWidget( {
12874 * data: 'Option 4',
12875 * label: 'Option Four'
12877 * new OO.ui.MenuOptionWidget( {
12878 * data: 'Option 5',
12879 * label: 'Option Five'
12884 * $( 'body' ).append( capsule.$element );
12886 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
12889 * @extends OO.ui.Widget
12890 * @mixins OO.ui.mixin.TabIndexedElement
12891 * @mixins OO.ui.mixin.GroupElement
12894 * @param {Object} [config] Configuration options
12895 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
12896 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
12897 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
12898 * If specified, this popup will be shown instead of the menu (but the menu
12899 * will still be used for item labels and allowArbitrary=false). The widgets
12900 * in the popup should use this.addItemsFromData() or this.addItems() as necessary.
12901 * @cfg {jQuery} [$overlay] Render the menu or popup into a separate layer.
12902 * This configuration is useful in cases where the expanded menu is larger than
12903 * its containing `<div>`. The specified overlay layer is usually on top of
12904 * the containing `<div>` and has a larger area. By default, the menu uses
12905 * relative positioning.
12907 OO
.ui
.CapsuleMultiSelectWidget
= function OoUiCapsuleMultiSelectWidget( config
) {
12910 // Configuration initialization
12911 config
= config
|| {};
12913 // Parent constructor
12914 OO
.ui
.CapsuleMultiSelectWidget
.parent
.call( this, config
);
12916 // Properties (must be set before mixin constructor calls)
12917 this.$input
= config
.popup
? null : $( '<input>' );
12918 this.$handle
= $( '<div>' );
12920 // Mixin constructors
12921 OO
.ui
.mixin
.GroupElement
.call( this, config
);
12922 if ( config
.popup
) {
12923 config
.popup
= $.extend( {}, config
.popup
, {
12927 OO
.ui
.mixin
.PopupElement
.call( this, config
);
12928 $tabFocus
= $( '<span>' );
12929 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: $tabFocus
} ) );
12933 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
12935 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
12936 OO
.ui
.mixin
.IconElement
.call( this, config
);
12939 this.allowArbitrary
= !!config
.allowArbitrary
;
12940 this.$overlay
= config
.$overlay
|| this.$element
;
12941 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
12944 $input
: this.$input
,
12945 $container
: this.$element
,
12946 filterFromInput
: true,
12947 disabled
: this.isDisabled()
12953 if ( this.popup
) {
12955 focus
: this.onFocusForPopup
.bind( this )
12957 this.popup
.$element
.on( 'focusout', this.onPopupFocusOut
.bind( this ) );
12958 if ( this.popup
.$autoCloseIgnore
) {
12959 this.popup
.$autoCloseIgnore
.on( 'focusout', this.onPopupFocusOut
.bind( this ) );
12961 this.popup
.connect( this, {
12962 toggle: function ( visible
) {
12963 $tabFocus
.toggle( !visible
);
12968 focus
: this.onInputFocus
.bind( this ),
12969 blur
: this.onInputBlur
.bind( this ),
12970 'propertychange change click mouseup keydown keyup input cut paste select': this.onInputChange
.bind( this ),
12971 keydown
: this.onKeyDown
.bind( this ),
12972 keypress
: this.onKeyPress
.bind( this )
12975 this.menu
.connect( this, {
12976 choose
: 'onMenuChoose',
12977 add
: 'onMenuItemsChange',
12978 remove
: 'onMenuItemsChange'
12981 click
: this.onClick
.bind( this )
12985 if ( this.$input
) {
12986 this.$input
.prop( 'disabled', this.isDisabled() );
12987 this.$input
.attr( {
12989 'aria-autocomplete': 'list'
12991 this.$input
.width( '1em' );
12993 if ( config
.data
) {
12994 this.setItemsFromData( config
.data
);
12996 this.$group
.addClass( 'oo-ui-capsuleMultiSelectWidget-group' );
12997 this.$handle
.addClass( 'oo-ui-capsuleMultiSelectWidget-handle' )
12998 .append( this.$indicator
, this.$icon
, this.$group
);
12999 this.$element
.addClass( 'oo-ui-capsuleMultiSelectWidget' )
13000 .append( this.$handle
);
13001 if ( this.popup
) {
13002 this.$handle
.append( $tabFocus
);
13003 this.$overlay
.append( this.popup
.$element
);
13005 this.$handle
.append( this.$input
);
13006 this.$overlay
.append( this.menu
.$element
);
13008 this.onMenuItemsChange();
13013 OO
.inheritClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.Widget
);
13014 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.GroupElement
);
13015 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.PopupElement
);
13016 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13017 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.IndicatorElement
);
13018 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.IconElement
);
13025 * A change event is emitted when the set of selected items changes.
13027 * @param {Mixed[]} datas Data of the now-selected items
13033 * Get the data of the items in the capsule
13034 * @return {Mixed[]}
13036 OO
.ui
.CapsuleMultiSelectWidget
.prototype.getItemsData = function () {
13037 return $.map( this.getItems(), function ( e
) { return e
.data
; } );
13041 * Set the items in the capsule by providing data
13043 * @param {Mixed[]} datas
13044 * @return {OO.ui.CapsuleMultiSelectWidget}
13046 OO
.ui
.CapsuleMultiSelectWidget
.prototype.setItemsFromData = function ( datas
) {
13049 items
= this.getItems();
13051 $.each( datas
, function ( i
, data
) {
13053 item
= menu
.getItemFromData( data
);
13056 label
= item
.label
;
13057 } else if ( widget
.allowArbitrary
) {
13058 label
= String( data
);
13064 for ( j
= 0; j
< items
.length
; j
++ ) {
13065 if ( items
[ j
].data
=== data
&& items
[ j
].label
=== label
) {
13067 items
.splice( j
, 1 );
13072 item
= new OO
.ui
.CapsuleItemWidget( { data
: data
, label
: label
} );
13074 widget
.addItems( [ item
], i
);
13077 if ( items
.length
) {
13078 widget
.removeItems( items
);
13085 * Add items to the capsule by providing their data
13087 * @param {Mixed[]} datas
13088 * @return {OO.ui.CapsuleMultiSelectWidget}
13090 OO
.ui
.CapsuleMultiSelectWidget
.prototype.addItemsFromData = function ( datas
) {
13095 $.each( datas
, function ( i
, data
) {
13098 if ( !widget
.getItemFromData( data
) ) {
13099 item
= menu
.getItemFromData( data
);
13101 items
.push( new OO
.ui
.CapsuleItemWidget( { data
: data
, label
: item
.label
} ) );
13102 } else if ( widget
.allowArbitrary
) {
13103 items
.push( new OO
.ui
.CapsuleItemWidget( { data
: data
, label
: String( data
) } ) );
13108 if ( items
.length
) {
13109 this.addItems( items
);
13116 * Remove items by data
13118 * @param {Mixed[]} datas
13119 * @return {OO.ui.CapsuleMultiSelectWidget}
13121 OO
.ui
.CapsuleMultiSelectWidget
.prototype.removeItemsFromData = function ( datas
) {
13125 $.each( datas
, function ( i
, data
) {
13126 var item
= widget
.getItemFromData( data
);
13128 items
.push( item
);
13132 if ( items
.length
) {
13133 this.removeItems( items
);
13142 OO
.ui
.CapsuleMultiSelectWidget
.prototype.addItems = function ( items
) {
13144 oldItems
= this.items
.slice();
13146 OO
.ui
.mixin
.GroupElement
.prototype.addItems
.call( this, items
);
13148 if ( this.items
.length
!== oldItems
.length
) {
13152 for ( i
= 0, l
= oldItems
.length
; same
&& i
< l
; i
++ ) {
13153 same
= same
&& this.items
[ i
] === oldItems
[ i
];
13157 this.emit( 'change', this.getItemsData() );
13166 OO
.ui
.CapsuleMultiSelectWidget
.prototype.removeItems = function ( items
) {
13168 oldItems
= this.items
.slice();
13170 OO
.ui
.mixin
.GroupElement
.prototype.removeItems
.call( this, items
);
13172 if ( this.items
.length
!== oldItems
.length
) {
13176 for ( i
= 0, l
= oldItems
.length
; same
&& i
< l
; i
++ ) {
13177 same
= same
&& this.items
[ i
] === oldItems
[ i
];
13181 this.emit( 'change', this.getItemsData() );
13190 OO
.ui
.CapsuleMultiSelectWidget
.prototype.clearItems = function () {
13191 if ( this.items
.length
) {
13192 OO
.ui
.mixin
.GroupElement
.prototype.clearItems
.call( this );
13193 this.emit( 'change', this.getItemsData() );
13199 * Get the capsule widget's menu.
13200 * @return {OO.ui.MenuSelectWidget} Menu widget
13202 OO
.ui
.CapsuleMultiSelectWidget
.prototype.getMenu = function () {
13207 * Handle focus events
13210 * @param {jQuery.Event} event
13212 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onInputFocus = function () {
13213 if ( !this.isDisabled() ) {
13214 this.menu
.toggle( true );
13219 * Handle blur events
13222 * @param {jQuery.Event} event
13224 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onInputBlur = function () {
13229 * Handle focus events
13232 * @param {jQuery.Event} event
13234 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onFocusForPopup = function () {
13235 if ( !this.isDisabled() ) {
13236 this.popup
.setSize( this.$handle
.width() );
13237 this.popup
.toggle( true );
13238 this.popup
.$element
.find( '*' )
13239 .filter( function () { return OO
.ui
.isFocusableElement( $( this ), true ); } )
13246 * Handles popup focus out events.
13249 * @param {Event} e Focus out event
13251 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onPopupFocusOut = function () {
13252 var widget
= this.popup
;
13254 setTimeout( function () {
13256 widget
.isVisible() &&
13257 !OO
.ui
.contains( widget
.$element
[ 0 ], document
.activeElement
, true ) &&
13258 ( !widget
.$autoCloseIgnore
|| !widget
.$autoCloseIgnore
.has( document
.activeElement
).length
)
13260 widget
.toggle( false );
13266 * Handle mouse click events.
13269 * @param {jQuery.Event} e Mouse click event
13271 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onClick = function ( e
) {
13272 if ( e
.which
=== 1 ) {
13279 * Handle key press events.
13282 * @param {jQuery.Event} e Key press event
13284 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onKeyPress = function ( e
) {
13287 if ( !this.isDisabled() ) {
13288 if ( e
.which
=== OO
.ui
.Keys
.ESCAPE
) {
13293 if ( !this.popup
) {
13294 this.menu
.toggle( true );
13295 if ( e
.which
=== OO
.ui
.Keys
.ENTER
) {
13296 item
= this.menu
.getItemFromLabel( this.$input
.val(), true );
13298 this.addItemsFromData( [ item
.data
] );
13300 } else if ( this.allowArbitrary
&& this.$input
.val().trim() !== '' ) {
13301 this.addItemsFromData( [ this.$input
.val() ] );
13307 // Make sure the input gets resized.
13308 setTimeout( this.onInputChange
.bind( this ), 0 );
13314 * Handle key down events.
13317 * @param {jQuery.Event} e Key down event
13319 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onKeyDown = function ( e
) {
13320 if ( !this.isDisabled() ) {
13321 // 'keypress' event is not triggered for Backspace
13322 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.$input
.val() === '' ) {
13323 if ( this.items
.length
) {
13324 this.removeItems( this.items
.slice( -1 ) );
13332 * Handle input change events.
13335 * @param {jQuery.Event} e Event of some sort
13337 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onInputChange = function () {
13338 if ( !this.isDisabled() ) {
13339 this.$input
.width( this.$input
.val().length
+ 'em' );
13344 * Handle menu choose events.
13347 * @param {OO.ui.OptionWidget} item Chosen item
13349 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onMenuChoose = function ( item
) {
13350 if ( item
&& item
.isVisible() ) {
13351 this.addItemsFromData( [ item
.getData() ] );
13357 * Handle menu item change events.
13361 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onMenuItemsChange = function () {
13362 this.setItemsFromData( this.getItemsData() );
13363 this.$element
.toggleClass( 'oo-ui-capsuleMultiSelectWidget-empty', this.menu
.isEmpty() );
13367 * Clear the input field
13370 OO
.ui
.CapsuleMultiSelectWidget
.prototype.clearInput = function () {
13371 if ( this.$input
) {
13372 this.$input
.val( '' );
13373 this.$input
.width( '1em' );
13375 if ( this.popup
) {
13376 this.popup
.toggle( false );
13378 this.menu
.toggle( false );
13379 this.menu
.selectItem();
13380 this.menu
.highlightItem();
13386 OO
.ui
.CapsuleMultiSelectWidget
.prototype.setDisabled = function ( disabled
) {
13390 OO
.ui
.CapsuleMultiSelectWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
13392 if ( this.$input
) {
13393 this.$input
.prop( 'disabled', this.isDisabled() );
13396 this.menu
.setDisabled( this.isDisabled() );
13398 if ( this.popup
) {
13399 this.popup
.setDisabled( this.isDisabled() );
13402 if ( this.items
) {
13403 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
13404 this.items
[ i
].updateDisabled();
13414 * @return {OO.ui.CapsuleMultiSelectWidget}
13416 OO
.ui
.CapsuleMultiSelectWidget
.prototype.focus = function () {
13417 if ( !this.isDisabled() ) {
13418 if ( this.popup
) {
13419 this.popup
.setSize( this.$handle
.width() );
13420 this.popup
.toggle( true );
13421 this.popup
.$element
.find( '*' )
13422 .filter( function () { return OO
.ui
.isFocusableElement( $( this ), true ); } )
13426 this.menu
.toggle( true );
13427 this.$input
.focus();
13434 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiSelectWidget
13435 * CapsuleMultiSelectWidget} to display the selected items.
13438 * @extends OO.ui.Widget
13439 * @mixins OO.ui.mixin.ItemWidget
13440 * @mixins OO.ui.mixin.IndicatorElement
13441 * @mixins OO.ui.mixin.LabelElement
13442 * @mixins OO.ui.mixin.FlaggedElement
13443 * @mixins OO.ui.mixin.TabIndexedElement
13446 * @param {Object} [config] Configuration options
13448 OO
.ui
.CapsuleItemWidget
= function OoUiCapsuleItemWidget( config
) {
13449 // Configuration initialization
13450 config
= config
|| {};
13452 // Parent constructor
13453 OO
.ui
.CapsuleItemWidget
.parent
.call( this, config
);
13455 // Properties (must be set before mixin constructor calls)
13456 this.$indicator
= $( '<span>' );
13458 // Mixin constructors
13459 OO
.ui
.mixin
.ItemWidget
.call( this );
13460 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$indicator
, indicator
: 'clear' } ) );
13461 OO
.ui
.mixin
.LabelElement
.call( this, config
);
13462 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
13463 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$indicator
} ) );
13466 this.$indicator
.on( {
13467 keydown
: this.onCloseKeyDown
.bind( this ),
13468 click
: this.onCloseClick
.bind( this )
13470 this.$element
.on( 'click', false );
13474 .addClass( 'oo-ui-capsuleItemWidget' )
13475 .append( this.$indicator
, this.$label
);
13480 OO
.inheritClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.Widget
);
13481 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.ItemWidget
);
13482 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.IndicatorElement
);
13483 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.LabelElement
);
13484 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.FlaggedElement
);
13485 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13490 * Handle close icon clicks
13491 * @param {jQuery.Event} event
13493 OO
.ui
.CapsuleItemWidget
.prototype.onCloseClick = function () {
13494 var element
= this.getElementGroup();
13496 if ( !this.isDisabled() && element
&& $.isFunction( element
.removeItems
) ) {
13497 element
.removeItems( [ this ] );
13503 * Handle close keyboard events
13504 * @param {jQuery.Event} event Key down event
13506 OO
.ui
.CapsuleItemWidget
.prototype.onCloseKeyDown = function ( e
) {
13507 if ( !this.isDisabled() && $.isFunction( this.getElementGroup().removeItems
) ) {
13508 switch ( e
.which
) {
13509 case OO
.ui
.Keys
.ENTER
:
13510 case OO
.ui
.Keys
.BACKSPACE
:
13511 case OO
.ui
.Keys
.SPACE
:
13512 this.getElementGroup().removeItems( [ this ] );
13519 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
13520 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
13521 * users can interact with it.
13523 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
13524 * OO.ui.DropdownInputWidget instead.
13527 * // Example: A DropdownWidget with a menu that contains three options
13528 * var dropDown = new OO.ui.DropdownWidget( {
13529 * label: 'Dropdown menu: Select a menu option',
13532 * new OO.ui.MenuOptionWidget( {
13536 * new OO.ui.MenuOptionWidget( {
13540 * new OO.ui.MenuOptionWidget( {
13548 * $( 'body' ).append( dropDown.$element );
13550 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
13552 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13555 * @extends OO.ui.Widget
13556 * @mixins OO.ui.mixin.IconElement
13557 * @mixins OO.ui.mixin.IndicatorElement
13558 * @mixins OO.ui.mixin.LabelElement
13559 * @mixins OO.ui.mixin.TitledElement
13560 * @mixins OO.ui.mixin.TabIndexedElement
13563 * @param {Object} [config] Configuration options
13564 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
13565 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
13566 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
13567 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
13569 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
13570 // Configuration initialization
13571 config
= $.extend( { indicator
: 'down' }, config
);
13573 // Parent constructor
13574 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
13576 // Properties (must be set before TabIndexedElement constructor call)
13577 this.$handle
= this.$( '<span>' );
13578 this.$overlay
= config
.$overlay
|| this.$element
;
13580 // Mixin constructors
13581 OO
.ui
.mixin
.IconElement
.call( this, config
);
13582 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
13583 OO
.ui
.mixin
.LabelElement
.call( this, config
);
13584 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
13585 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
13588 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend( {
13590 $container
: this.$element
13591 }, config
.menu
) );
13595 click
: this.onClick
.bind( this ),
13596 keypress
: this.onKeyPress
.bind( this )
13598 this.menu
.connect( this, { select
: 'onMenuSelect' } );
13602 .addClass( 'oo-ui-dropdownWidget-handle' )
13603 .append( this.$icon
, this.$label
, this.$indicator
);
13605 .addClass( 'oo-ui-dropdownWidget' )
13606 .append( this.$handle
);
13607 this.$overlay
.append( this.menu
.$element
);
13612 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
13613 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
13614 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
13615 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
13616 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
13617 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13624 * @return {OO.ui.MenuSelectWidget} Menu of widget
13626 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
13631 * Handles menu select events.
13634 * @param {OO.ui.MenuOptionWidget} item Selected menu item
13636 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
13640 this.setLabel( null );
13644 selectedLabel
= item
.getLabel();
13646 // If the label is a DOM element, clone it, because setLabel will append() it
13647 if ( selectedLabel
instanceof jQuery
) {
13648 selectedLabel
= selectedLabel
.clone();
13651 this.setLabel( selectedLabel
);
13655 * Handle mouse click events.
13658 * @param {jQuery.Event} e Mouse click event
13660 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
13661 if ( !this.isDisabled() && e
.which
=== 1 ) {
13662 this.menu
.toggle();
13668 * Handle key press events.
13671 * @param {jQuery.Event} e Key press event
13673 OO
.ui
.DropdownWidget
.prototype.onKeyPress = function ( e
) {
13674 if ( !this.isDisabled() &&
13675 ( ( e
.which
=== OO
.ui
.Keys
.SPACE
&& !this.menu
.isVisible() ) || e
.which
=== OO
.ui
.Keys
.ENTER
)
13677 this.menu
.toggle();
13683 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
13684 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
13685 * OO.ui.mixin.IndicatorElement indicators}.
13686 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
13689 * // Example of a file select widget
13690 * var selectFile = new OO.ui.SelectFileWidget();
13691 * $( 'body' ).append( selectFile.$element );
13693 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
13696 * @extends OO.ui.Widget
13697 * @mixins OO.ui.mixin.IconElement
13698 * @mixins OO.ui.mixin.IndicatorElement
13699 * @mixins OO.ui.mixin.PendingElement
13700 * @mixins OO.ui.mixin.LabelElement
13703 * @param {Object} [config] Configuration options
13704 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
13705 * @cfg {string} [placeholder] Text to display when no file is selected.
13706 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
13707 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
13708 * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
13709 * @cfg {boolean} [dragDropUI=false] Deprecated alias for showDropTarget
13711 OO
.ui
.SelectFileWidget
= function OoUiSelectFileWidget( config
) {
13714 // TODO: Remove in next release
13715 if ( config
&& config
.dragDropUI
) {
13716 config
.showDropTarget
= true;
13719 // Configuration initialization
13720 config
= $.extend( {
13722 placeholder
: OO
.ui
.msg( 'ooui-selectfile-placeholder' ),
13723 notsupported
: OO
.ui
.msg( 'ooui-selectfile-not-supported' ),
13725 showDropTarget
: false
13728 // Parent constructor
13729 OO
.ui
.SelectFileWidget
.parent
.call( this, config
);
13731 // Mixin constructors
13732 OO
.ui
.mixin
.IconElement
.call( this, config
);
13733 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
13734 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$info
} ) );
13735 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { autoFitLabel
: true } ) );
13738 this.$info
= $( '<span>' );
13741 this.showDropTarget
= config
.showDropTarget
;
13742 this.isSupported
= this.constructor.static.isSupported();
13743 this.currentFile
= null;
13744 if ( Array
.isArray( config
.accept
) ) {
13745 this.accept
= config
.accept
;
13747 this.accept
= null;
13749 this.placeholder
= config
.placeholder
;
13750 this.notsupported
= config
.notsupported
;
13751 this.onFileSelectedHandler
= this.onFileSelected
.bind( this );
13753 this.selectButton
= new OO
.ui
.ButtonWidget( {
13754 classes
: [ 'oo-ui-selectFileWidget-selectButton' ],
13755 label
: 'Select a file',
13756 disabled
: this.disabled
|| !this.isSupported
13759 this.clearButton
= new OO
.ui
.ButtonWidget( {
13760 classes
: [ 'oo-ui-selectFileWidget-clearButton' ],
13763 disabled
: this.disabled
13767 this.selectButton
.$button
.on( {
13768 keypress
: this.onKeyPress
.bind( this )
13770 this.clearButton
.connect( this, {
13771 click
: 'onClearClick'
13773 if ( config
.droppable
) {
13774 dragHandler
= this.onDragEnterOrOver
.bind( this );
13775 this.$element
.on( {
13776 dragenter
: dragHandler
,
13777 dragover
: dragHandler
,
13778 dragleave
: this.onDragLeave
.bind( this ),
13779 drop
: this.onDrop
.bind( this )
13786 this.$label
.addClass( 'oo-ui-selectFileWidget-label' );
13788 .addClass( 'oo-ui-selectFileWidget-info' )
13789 .append( this.$icon
, this.$label
, this.clearButton
.$element
, this.$indicator
);
13791 .addClass( 'oo-ui-selectFileWidget' )
13792 .append( this.$info
, this.selectButton
.$element
);
13793 if ( config
.droppable
&& config
.showDropTarget
) {
13794 this.$dropTarget
= $( '<div>' )
13795 .addClass( 'oo-ui-selectFileWidget-dropTarget' )
13796 .text( OO
.ui
.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
13798 click
: this.onDropTargetClick
.bind( this )
13800 this.$element
.prepend( this.$dropTarget
);
13806 OO
.inheritClass( OO
.ui
.SelectFileWidget
, OO
.ui
.Widget
);
13807 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.IconElement
);
13808 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.IndicatorElement
);
13809 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.PendingElement
);
13810 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.LabelElement
);
13812 /* Static Properties */
13815 * Check if this widget is supported
13818 * @return {boolean}
13820 OO
.ui
.SelectFileWidget
.static.isSupported = function () {
13822 if ( OO
.ui
.SelectFileWidget
.static.isSupportedCache
=== null ) {
13823 $input
= $( '<input type="file">' );
13824 OO
.ui
.SelectFileWidget
.static.isSupportedCache
= $input
[ 0 ].files
!== undefined;
13826 return OO
.ui
.SelectFileWidget
.static.isSupportedCache
;
13829 OO
.ui
.SelectFileWidget
.static.isSupportedCache
= null;
13836 * A change event is emitted when the on/off state of the toggle changes.
13838 * @param {File|null} value New value
13844 * Get the current value of the field
13846 * @return {File|null}
13848 OO
.ui
.SelectFileWidget
.prototype.getValue = function () {
13849 return this.currentFile
;
13853 * Set the current value of the field
13855 * @param {File|null} file File to select
13857 OO
.ui
.SelectFileWidget
.prototype.setValue = function ( file
) {
13858 if ( this.currentFile
!== file
) {
13859 this.currentFile
= file
;
13861 this.emit( 'change', this.currentFile
);
13866 * Update the user interface when a file is selected or unselected
13870 OO
.ui
.SelectFileWidget
.prototype.updateUI = function () {
13871 if ( !this.isSupported
) {
13872 this.$element
.addClass( 'oo-ui-selectFileWidget-notsupported' );
13873 this.$element
.removeClass( 'oo-ui-selectFileWidget-empty' );
13874 this.setLabel( this.notsupported
);
13876 this.$element
.addClass( 'oo-ui-selectFileWidget-supported' );
13877 if ( this.currentFile
) {
13878 this.$element
.removeClass( 'oo-ui-selectFileWidget-empty' );
13879 this.setLabel( this.currentFile
.name
+
13880 ( this.currentFile
.type
!== '' ? OO
.ui
.msg( 'ooui-semicolon-separator' ) + this.currentFile
.type
: '' )
13883 this.$element
.addClass( 'oo-ui-selectFileWidget-empty' );
13884 this.setLabel( this.placeholder
);
13888 if ( this.$input
) {
13889 this.$input
.attr( 'title', this.getLabel() );
13894 * Add the input to the widget
13898 OO
.ui
.SelectFileWidget
.prototype.addInput = function () {
13899 if ( this.$input
) {
13900 this.$input
.remove();
13903 if ( !this.isSupported
) {
13904 this.$input
= null;
13908 this.$input
= $( '<input type="file">' );
13909 this.$input
.on( 'change', this.onFileSelectedHandler
);
13910 this.$input
.attr( {
13912 title
: this.getLabel()
13914 if ( this.accept
) {
13915 this.$input
.attr( 'accept', this.accept
.join( ', ' ) );
13917 this.selectButton
.$button
.append( this.$input
);
13921 * Determine if we should accept this file
13924 * @param {string} File MIME type
13925 * @return {boolean}
13927 OO
.ui
.SelectFileWidget
.prototype.isAllowedType = function ( mimeType
) {
13930 if ( !this.accept
|| !mimeType
) {
13934 for ( i
= 0; i
< this.accept
.length
; i
++ ) {
13935 mimeTest
= this.accept
[ i
];
13936 if ( mimeTest
=== mimeType
) {
13938 } else if ( mimeTest
.substr( -2 ) === '/*' ) {
13939 mimeTest
= mimeTest
.substr( 0, mimeTest
.length
- 1 );
13940 if ( mimeType
.substr( 0, mimeTest
.length
) === mimeTest
) {
13950 * Handle file selection from the input
13953 * @param {jQuery.Event} e
13955 OO
.ui
.SelectFileWidget
.prototype.onFileSelected = function ( e
) {
13956 var file
= OO
.getProp( e
.target
, 'files', 0 ) || null;
13958 if ( file
&& !this.isAllowedType( file
.type
) ) {
13962 this.setValue( file
);
13967 * Handle clear button click events.
13971 OO
.ui
.SelectFileWidget
.prototype.onClearClick = function () {
13972 this.setValue( null );
13977 * Handle key press events.
13980 * @param {jQuery.Event} e Key press event
13982 OO
.ui
.SelectFileWidget
.prototype.onKeyPress = function ( e
) {
13983 if ( this.isSupported
&& !this.isDisabled() && this.$input
&&
13984 ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
13986 this.$input
.click();
13992 * Handle drop target click events.
13995 * @param {jQuery.Event} e Key press event
13997 OO
.ui
.SelectFileWidget
.prototype.onDropTargetClick = function () {
13998 if ( this.isSupported
&& !this.isDisabled() && this.$input
) {
13999 this.$input
.click();
14005 * Handle drag enter and over events
14008 * @param {jQuery.Event} e Drag event
14010 OO
.ui
.SelectFileWidget
.prototype.onDragEnterOrOver = function ( e
) {
14012 droppableFile
= false,
14013 dt
= e
.originalEvent
.dataTransfer
;
14015 e
.preventDefault();
14016 e
.stopPropagation();
14018 if ( this.isDisabled() || !this.isSupported
) {
14019 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14020 dt
.dropEffect
= 'none';
14024 // DataTransferItem and File both have a type property, but in Chrome files
14025 // have no information at this point.
14026 itemOrFile
= OO
.getProp( dt
, 'items', 0 ) || OO
.getProp( dt
, 'files', 0 );
14027 if ( itemOrFile
) {
14028 if ( this.isAllowedType( itemOrFile
.type
) ) {
14029 droppableFile
= true;
14031 // dt.types is Array-like, but not an Array
14032 } else if ( Array
.prototype.indexOf
.call( OO
.getProp( dt
, 'types' ) || [], 'Files' ) !== -1 ) {
14033 // File information is not available at this point for security so just assume
14034 // it is acceptable for now.
14035 // https://bugzilla.mozilla.org/show_bug.cgi?id=640534
14036 droppableFile
= true;
14039 this.$element
.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile
);
14040 if ( !droppableFile
) {
14041 dt
.dropEffect
= 'none';
14048 * Handle drag leave events
14051 * @param {jQuery.Event} e Drag event
14053 OO
.ui
.SelectFileWidget
.prototype.onDragLeave = function () {
14054 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14058 * Handle drop events
14061 * @param {jQuery.Event} e Drop event
14063 OO
.ui
.SelectFileWidget
.prototype.onDrop = function ( e
) {
14065 dt
= e
.originalEvent
.dataTransfer
;
14067 e
.preventDefault();
14068 e
.stopPropagation();
14069 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14071 if ( this.isDisabled() || !this.isSupported
) {
14075 file
= OO
.getProp( dt
, 'files', 0 );
14076 if ( file
&& !this.isAllowedType( file
.type
) ) {
14080 this.setValue( file
);
14089 OO
.ui
.SelectFileWidget
.prototype.setDisabled = function ( disabled
) {
14090 OO
.ui
.SelectFileWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
14091 if ( this.selectButton
) {
14092 this.selectButton
.setDisabled( disabled
);
14094 if ( this.clearButton
) {
14095 this.clearButton
.setDisabled( disabled
);
14101 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
14102 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
14103 * for a list of icons included in the library.
14106 * // An icon widget with a label
14107 * var myIcon = new OO.ui.IconWidget( {
14109 * iconTitle: 'Help'
14111 * // Create a label.
14112 * var iconLabel = new OO.ui.LabelWidget( {
14115 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
14117 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
14120 * @extends OO.ui.Widget
14121 * @mixins OO.ui.mixin.IconElement
14122 * @mixins OO.ui.mixin.TitledElement
14123 * @mixins OO.ui.mixin.FlaggedElement
14126 * @param {Object} [config] Configuration options
14128 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
14129 // Configuration initialization
14130 config
= config
|| {};
14132 // Parent constructor
14133 OO
.ui
.IconWidget
.parent
.call( this, config
);
14135 // Mixin constructors
14136 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
14137 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
14138 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
14141 this.$element
.addClass( 'oo-ui-iconWidget' );
14146 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
14147 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
14148 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
14149 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
14151 /* Static Properties */
14153 OO
.ui
.IconWidget
.static.tagName
= 'span';
14156 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
14157 * attention to the status of an item or to clarify the function of a control. For a list of
14158 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
14161 * // Example of an indicator widget
14162 * var indicator1 = new OO.ui.IndicatorWidget( {
14163 * indicator: 'alert'
14166 * // Create a fieldset layout to add a label
14167 * var fieldset = new OO.ui.FieldsetLayout();
14168 * fieldset.addItems( [
14169 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
14171 * $( 'body' ).append( fieldset.$element );
14173 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
14176 * @extends OO.ui.Widget
14177 * @mixins OO.ui.mixin.IndicatorElement
14178 * @mixins OO.ui.mixin.TitledElement
14181 * @param {Object} [config] Configuration options
14183 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
14184 // Configuration initialization
14185 config
= config
|| {};
14187 // Parent constructor
14188 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
14190 // Mixin constructors
14191 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
14192 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
14195 this.$element
.addClass( 'oo-ui-indicatorWidget' );
14200 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
14201 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
14202 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
14204 /* Static Properties */
14206 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
14209 * InputWidget is the base class for all input widgets, which
14210 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
14211 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
14212 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14214 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14218 * @extends OO.ui.Widget
14219 * @mixins OO.ui.mixin.FlaggedElement
14220 * @mixins OO.ui.mixin.TabIndexedElement
14221 * @mixins OO.ui.mixin.TitledElement
14222 * @mixins OO.ui.mixin.AccessKeyedElement
14225 * @param {Object} [config] Configuration options
14226 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
14227 * @cfg {string} [value=''] The value of the input.
14228 * @cfg {string} [accessKey=''] The access key of the input.
14229 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
14230 * before it is accepted.
14232 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
14233 // Configuration initialization
14234 config
= config
|| {};
14236 // Parent constructor
14237 OO
.ui
.InputWidget
.parent
.call( this, config
);
14240 this.$input
= this.getInputElement( config
);
14242 this.inputFilter
= config
.inputFilter
;
14244 // Mixin constructors
14245 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
14246 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
14247 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
14248 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$input
} ) );
14251 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
14255 .addClass( 'oo-ui-inputWidget-input' )
14256 .attr( 'name', config
.name
)
14257 .prop( 'disabled', this.isDisabled() );
14259 .addClass( 'oo-ui-inputWidget' )
14260 .append( this.$input
);
14261 this.setValue( config
.value
);
14262 this.setAccessKey( config
.accessKey
);
14267 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
14268 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
14269 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
14270 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
14271 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
14273 /* Static Properties */
14275 OO
.ui
.InputWidget
.static.supportsSimpleLabel
= true;
14282 * A change event is emitted when the value of the input changes.
14284 * @param {string} value
14290 * Get input element.
14292 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
14293 * different circumstances. The element must have a `value` property (like form elements).
14296 * @param {Object} config Configuration options
14297 * @return {jQuery} Input element
14299 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
14300 return $( '<input>' );
14304 * Handle potentially value-changing events.
14307 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
14309 OO
.ui
.InputWidget
.prototype.onEdit = function () {
14311 if ( !this.isDisabled() ) {
14312 // Allow the stack to clear so the value will be updated
14313 setTimeout( function () {
14314 widget
.setValue( widget
.$input
.val() );
14320 * Get the value of the input.
14322 * @return {string} Input value
14324 OO
.ui
.InputWidget
.prototype.getValue = function () {
14325 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14326 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14327 var value
= this.$input
.val();
14328 if ( this.value
!== value
) {
14329 this.setValue( value
);
14335 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
14337 * @param {boolean} isRTL
14338 * Direction is right-to-left
14340 OO
.ui
.InputWidget
.prototype.setRTL = function ( isRTL
) {
14341 this.$input
.prop( 'dir', isRTL
? 'rtl' : 'ltr' );
14345 * Set the value of the input.
14347 * @param {string} value New value
14351 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
14352 value
= this.cleanUpValue( value
);
14353 // Update the DOM if it has changed. Note that with cleanUpValue, it
14354 // is possible for the DOM value to change without this.value changing.
14355 if ( this.$input
.val() !== value
) {
14356 this.$input
.val( value
);
14358 if ( this.value
!== value
) {
14359 this.value
= value
;
14360 this.emit( 'change', this.value
);
14366 * Set the input's access key.
14367 * FIXME: This is the same code as in OO.ui.mixin.ButtonElement, maybe find a better place for it?
14369 * @param {string} accessKey Input's access key, use empty string to remove
14372 OO
.ui
.InputWidget
.prototype.setAccessKey = function ( accessKey
) {
14373 accessKey
= typeof accessKey
=== 'string' && accessKey
.length
? accessKey
: null;
14375 if ( this.accessKey
!== accessKey
) {
14376 if ( this.$input
) {
14377 if ( accessKey
!== null ) {
14378 this.$input
.attr( 'accesskey', accessKey
);
14380 this.$input
.removeAttr( 'accesskey' );
14383 this.accessKey
= accessKey
;
14390 * Clean up incoming value.
14392 * Ensures value is a string, and converts undefined and null to empty string.
14395 * @param {string} value Original value
14396 * @return {string} Cleaned up value
14398 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
14399 if ( value
=== undefined || value
=== null ) {
14401 } else if ( this.inputFilter
) {
14402 return this.inputFilter( String( value
) );
14404 return String( value
);
14409 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
14410 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
14413 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
14414 if ( !this.isDisabled() ) {
14415 if ( this.$input
.is( ':checkbox, :radio' ) ) {
14416 this.$input
.click();
14418 if ( this.$input
.is( ':input' ) ) {
14419 this.$input
[ 0 ].focus();
14427 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
14428 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
14429 if ( this.$input
) {
14430 this.$input
.prop( 'disabled', this.isDisabled() );
14440 OO
.ui
.InputWidget
.prototype.focus = function () {
14441 this.$input
[ 0 ].focus();
14450 OO
.ui
.InputWidget
.prototype.blur = function () {
14451 this.$input
[ 0 ].blur();
14458 OO
.ui
.InputWidget
.prototype.gatherPreInfuseState = function ( node
) {
14460 state
= OO
.ui
.InputWidget
.parent
.prototype.gatherPreInfuseState
.call( this, node
),
14461 $input
= state
.$input
|| $( node
).find( '.oo-ui-inputWidget-input' );
14462 state
.value
= $input
.val();
14463 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
14464 state
.focus
= $input
.is( ':focus' );
14471 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
14472 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
14473 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
14474 this.setValue( state
.value
);
14476 if ( state
.focus
) {
14482 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
14483 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
14484 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
14485 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
14486 * [OOjs UI documentation on MediaWiki] [1] for more information.
14489 * // A ButtonInputWidget rendered as an HTML button, the default.
14490 * var button = new OO.ui.ButtonInputWidget( {
14491 * label: 'Input button',
14495 * $( 'body' ).append( button.$element );
14497 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
14500 * @extends OO.ui.InputWidget
14501 * @mixins OO.ui.mixin.ButtonElement
14502 * @mixins OO.ui.mixin.IconElement
14503 * @mixins OO.ui.mixin.IndicatorElement
14504 * @mixins OO.ui.mixin.LabelElement
14505 * @mixins OO.ui.mixin.TitledElement
14508 * @param {Object} [config] Configuration options
14509 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
14510 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
14511 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
14512 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
14513 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
14515 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
14516 // Configuration initialization
14517 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
14519 // Properties (must be set before parent constructor, which calls #setValue)
14520 this.useInputTag
= config
.useInputTag
;
14522 // Parent constructor
14523 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
14525 // Mixin constructors
14526 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
14527 OO
.ui
.mixin
.IconElement
.call( this, config
);
14528 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
14529 OO
.ui
.mixin
.LabelElement
.call( this, config
);
14530 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
14533 if ( !config
.useInputTag
) {
14534 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
14536 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
14541 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
14542 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
14543 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
14544 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
14545 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
14546 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
14548 /* Static Properties */
14551 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
14552 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
14554 OO
.ui
.ButtonInputWidget
.static.supportsSimpleLabel
= false;
14562 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
14563 var type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ?
14566 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
14572 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
14574 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
14575 * text, or `null` for no label
14578 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
14579 OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
14581 if ( this.useInputTag
) {
14582 if ( typeof label
=== 'function' ) {
14583 label
= OO
.ui
.resolveMsg( label
);
14585 if ( label
instanceof jQuery
) {
14586 label
= label
.text();
14591 this.$input
.val( label
);
14598 * Set the value of the input.
14600 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
14601 * they do not support {@link #value values}.
14603 * @param {string} value New value
14606 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
14607 if ( !this.useInputTag
) {
14608 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
14614 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
14615 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
14616 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
14617 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
14619 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
14622 * // An example of selected, unselected, and disabled checkbox inputs
14623 * var checkbox1=new OO.ui.CheckboxInputWidget( {
14627 * var checkbox2=new OO.ui.CheckboxInputWidget( {
14630 * var checkbox3=new OO.ui.CheckboxInputWidget( {
14634 * // Create a fieldset layout with fields for each checkbox.
14635 * var fieldset = new OO.ui.FieldsetLayout( {
14636 * label: 'Checkboxes'
14638 * fieldset.addItems( [
14639 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
14640 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
14641 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
14643 * $( 'body' ).append( fieldset.$element );
14645 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14648 * @extends OO.ui.InputWidget
14651 * @param {Object} [config] Configuration options
14652 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
14654 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
14655 // Configuration initialization
14656 config
= config
|| {};
14658 // Parent constructor
14659 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
14663 .addClass( 'oo-ui-checkboxInputWidget' )
14664 // Required for pretty styling in MediaWiki theme
14665 .append( $( '<span>' ) );
14666 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
14671 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
14679 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
14680 return $( '<input type="checkbox" />' );
14686 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
14688 if ( !this.isDisabled() ) {
14689 // Allow the stack to clear so the value will be updated
14690 setTimeout( function () {
14691 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
14697 * Set selection state of this checkbox.
14699 * @param {boolean} state `true` for selected
14702 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
14704 if ( this.selected
!== state
) {
14705 this.selected
= state
;
14706 this.$input
.prop( 'checked', this.selected
);
14707 this.emit( 'change', this.selected
);
14713 * Check if this checkbox is selected.
14715 * @return {boolean} Checkbox is selected
14717 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
14718 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14719 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14720 var selected
= this.$input
.prop( 'checked' );
14721 if ( this.selected
!== selected
) {
14722 this.setSelected( selected
);
14724 return this.selected
;
14730 OO
.ui
.CheckboxInputWidget
.prototype.gatherPreInfuseState = function ( node
) {
14732 state
= OO
.ui
.CheckboxInputWidget
.parent
.prototype.gatherPreInfuseState
.call( this, node
),
14733 $input
= $( node
).find( '.oo-ui-inputWidget-input' );
14734 state
.$input
= $input
; // shortcut for performance, used in InputWidget
14735 state
.checked
= $input
.prop( 'checked' );
14742 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
14743 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
14744 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
14745 this.setSelected( state
.checked
);
14750 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
14751 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
14752 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
14753 * more information about input widgets.
14755 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
14756 * are no options. If no `value` configuration option is provided, the first option is selected.
14757 * If you need a state representing no value (no option being selected), use a DropdownWidget.
14759 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
14762 * // Example: A DropdownInputWidget with three options
14763 * var dropdownInput = new OO.ui.DropdownInputWidget( {
14765 * { data: 'a', label: 'First' },
14766 * { data: 'b', label: 'Second'},
14767 * { data: 'c', label: 'Third' }
14770 * $( 'body' ).append( dropdownInput.$element );
14772 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14775 * @extends OO.ui.InputWidget
14776 * @mixins OO.ui.mixin.TitledElement
14779 * @param {Object} [config] Configuration options
14780 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
14781 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
14783 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
14784 // Configuration initialization
14785 config
= config
|| {};
14787 // Properties (must be done before parent constructor which calls #setDisabled)
14788 this.dropdownWidget
= new OO
.ui
.DropdownWidget( config
.dropdown
);
14790 // Parent constructor
14791 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
14793 // Mixin constructors
14794 OO
.ui
.mixin
.TitledElement
.call( this, config
);
14797 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
14800 this.setOptions( config
.options
|| [] );
14802 .addClass( 'oo-ui-dropdownInputWidget' )
14803 .append( this.dropdownWidget
.$element
);
14808 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
14809 OO
.mixinClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.mixin
.TitledElement
);
14817 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
14818 return $( '<input type="hidden">' );
14822 * Handles menu select events.
14825 * @param {OO.ui.MenuOptionWidget} item Selected menu item
14827 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
14828 this.setValue( item
.getData() );
14834 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
14835 value
= this.cleanUpValue( value
);
14836 this.dropdownWidget
.getMenu().selectItemByData( value
);
14837 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
14844 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
14845 this.dropdownWidget
.setDisabled( state
);
14846 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
14851 * Set the options available for this input.
14853 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
14856 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
14858 value
= this.getValue(),
14861 // Rebuild the dropdown menu
14862 this.dropdownWidget
.getMenu()
14864 .addItems( options
.map( function ( opt
) {
14865 var optValue
= widget
.cleanUpValue( opt
.data
);
14866 return new OO
.ui
.MenuOptionWidget( {
14868 label
: opt
.label
!== undefined ? opt
.label
: optValue
14872 // Restore the previous value, or reset to something sensible
14873 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
14874 // Previous value is still available, ensure consistency with the dropdown
14875 this.setValue( value
);
14877 // No longer valid, reset
14878 if ( options
.length
) {
14879 this.setValue( options
[ 0 ].data
);
14889 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
14890 this.dropdownWidget
.getMenu().toggle( true );
14897 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
14898 this.dropdownWidget
.getMenu().toggle( false );
14903 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
14904 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
14905 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
14906 * please see the [OOjs UI documentation on MediaWiki][1].
14908 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
14911 * // An example of selected, unselected, and disabled radio inputs
14912 * var radio1 = new OO.ui.RadioInputWidget( {
14916 * var radio2 = new OO.ui.RadioInputWidget( {
14919 * var radio3 = new OO.ui.RadioInputWidget( {
14923 * // Create a fieldset layout with fields for each radio button.
14924 * var fieldset = new OO.ui.FieldsetLayout( {
14925 * label: 'Radio inputs'
14927 * fieldset.addItems( [
14928 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
14929 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
14930 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
14932 * $( 'body' ).append( fieldset.$element );
14934 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14937 * @extends OO.ui.InputWidget
14940 * @param {Object} [config] Configuration options
14941 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
14943 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
14944 // Configuration initialization
14945 config
= config
|| {};
14947 // Parent constructor
14948 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
14952 .addClass( 'oo-ui-radioInputWidget' )
14953 // Required for pretty styling in MediaWiki theme
14954 .append( $( '<span>' ) );
14955 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
14960 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
14968 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
14969 return $( '<input type="radio" />' );
14975 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
14976 // RadioInputWidget doesn't track its state.
14980 * Set selection state of this radio button.
14982 * @param {boolean} state `true` for selected
14985 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
14986 // RadioInputWidget doesn't track its state.
14987 this.$input
.prop( 'checked', state
);
14992 * Check if this radio button is selected.
14994 * @return {boolean} Radio is selected
14996 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
14997 return this.$input
.prop( 'checked' );
15003 OO
.ui
.RadioInputWidget
.prototype.gatherPreInfuseState = function ( node
) {
15005 state
= OO
.ui
.RadioInputWidget
.parent
.prototype.gatherPreInfuseState
.call( this, node
),
15006 $input
= $( node
).find( '.oo-ui-inputWidget-input' );
15007 state
.$input
= $input
; // shortcut for performance, used in InputWidget
15008 state
.checked
= $input
.prop( 'checked' );
15015 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
15016 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
15017 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
15018 this.setSelected( state
.checked
);
15023 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
15024 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15025 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15026 * more information about input widgets.
15028 * This and OO.ui.DropdownInputWidget support the same configuration options.
15031 * // Example: A RadioSelectInputWidget with three options
15032 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
15034 * { data: 'a', label: 'First' },
15035 * { data: 'b', label: 'Second'},
15036 * { data: 'c', label: 'Third' }
15039 * $( 'body' ).append( radioSelectInput.$element );
15041 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15044 * @extends OO.ui.InputWidget
15047 * @param {Object} [config] Configuration options
15048 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15050 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
15051 // Configuration initialization
15052 config
= config
|| {};
15054 // Properties (must be done before parent constructor which calls #setDisabled)
15055 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
15057 // Parent constructor
15058 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
15061 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
15064 this.setOptions( config
.options
|| [] );
15066 .addClass( 'oo-ui-radioSelectInputWidget' )
15067 .append( this.radioSelectWidget
.$element
);
15072 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
15074 /* Static Properties */
15076 OO
.ui
.RadioSelectInputWidget
.static.supportsSimpleLabel
= false;
15084 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
15085 return $( '<input type="hidden">' );
15089 * Handles menu select events.
15092 * @param {OO.ui.RadioOptionWidget} item Selected menu item
15094 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
15095 this.setValue( item
.getData() );
15101 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
15102 value
= this.cleanUpValue( value
);
15103 this.radioSelectWidget
.selectItemByData( value
);
15104 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
15111 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
15112 this.radioSelectWidget
.setDisabled( state
);
15113 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
15118 * Set the options available for this input.
15120 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15123 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
15125 value
= this.getValue(),
15128 // Rebuild the radioSelect menu
15129 this.radioSelectWidget
15131 .addItems( options
.map( function ( opt
) {
15132 var optValue
= widget
.cleanUpValue( opt
.data
);
15133 return new OO
.ui
.RadioOptionWidget( {
15135 label
: opt
.label
!== undefined ? opt
.label
: optValue
15139 // Restore the previous value, or reset to something sensible
15140 if ( this.radioSelectWidget
.getItemFromData( value
) ) {
15141 // Previous value is still available, ensure consistency with the radioSelect
15142 this.setValue( value
);
15144 // No longer valid, reset
15145 if ( options
.length
) {
15146 this.setValue( options
[ 0 ].data
);
15156 OO
.ui
.RadioSelectInputWidget
.prototype.gatherPreInfuseState = function ( node
) {
15157 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.prototype.gatherPreInfuseState
.call( this, node
);
15158 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
15163 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
15164 * size of the field as well as its presentation. In addition, these widgets can be configured
15165 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
15166 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
15167 * which modifies incoming values rather than validating them.
15168 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
15170 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15173 * // Example of a text input widget
15174 * var textInput = new OO.ui.TextInputWidget( {
15175 * value: 'Text input'
15177 * $( 'body' ).append( textInput.$element );
15179 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15182 * @extends OO.ui.InputWidget
15183 * @mixins OO.ui.mixin.IconElement
15184 * @mixins OO.ui.mixin.IndicatorElement
15185 * @mixins OO.ui.mixin.PendingElement
15186 * @mixins OO.ui.mixin.LabelElement
15189 * @param {Object} [config] Configuration options
15190 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
15191 * 'email' or 'url'. Ignored if `multiline` is true.
15193 * Some values of `type` result in additional behaviors:
15195 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
15196 * empties the text field
15197 * @cfg {string} [placeholder] Placeholder text
15198 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
15199 * instruct the browser to focus this widget.
15200 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
15201 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
15202 * @cfg {boolean} [multiline=false] Allow multiple lines of text
15203 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
15204 * specifies minimum number of rows to display.
15205 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
15206 * Use the #maxRows config to specify a maximum number of displayed rows.
15207 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
15208 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
15209 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
15210 * the value or placeholder text: `'before'` or `'after'`
15211 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
15212 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
15213 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
15214 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
15215 * (the value must contain only numbers); when RegExp, a regular expression that must match the
15216 * value for it to be considered valid; when Function, a function receiving the value as parameter
15217 * that must return true, or promise resolving to true, for it to be considered valid.
15219 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
15220 // Configuration initialization
15221 config
= $.extend( {
15223 labelPosition
: 'after'
15225 if ( config
.type
=== 'search' ) {
15226 if ( config
.icon
=== undefined ) {
15227 config
.icon
= 'search';
15229 // indicator: 'clear' is set dynamically later, depending on value
15231 if ( config
.required
) {
15232 if ( config
.indicator
=== undefined ) {
15233 config
.indicator
= 'required';
15237 // Parent constructor
15238 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
15240 // Mixin constructors
15241 OO
.ui
.mixin
.IconElement
.call( this, config
);
15242 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
15243 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
15244 OO
.ui
.mixin
.LabelElement
.call( this, config
);
15247 this.type
= this.getSaneType( config
);
15248 this.readOnly
= false;
15249 this.multiline
= !!config
.multiline
;
15250 this.autosize
= !!config
.autosize
;
15251 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
15252 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
15253 this.validate
= null;
15255 // Clone for resizing
15256 if ( this.autosize
) {
15257 this.$clone
= this.$input
15259 .insertAfter( this.$input
)
15260 .attr( 'aria-hidden', 'true' )
15261 .addClass( 'oo-ui-element-hidden' );
15264 this.setValidation( config
.validate
);
15265 this.setLabelPosition( config
.labelPosition
);
15269 keypress
: this.onKeyPress
.bind( this ),
15270 blur
: this.onBlur
.bind( this )
15273 focus
: this.onElementAttach
.bind( this )
15275 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
15276 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
15277 this.on( 'labelChange', this.updatePosition
.bind( this ) );
15278 this.connect( this, {
15279 change
: 'onChange',
15280 disable
: 'onDisable'
15285 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
15286 .append( this.$icon
, this.$indicator
);
15287 this.setReadOnly( !!config
.readOnly
);
15288 this.updateSearchIndicator();
15289 if ( config
.placeholder
) {
15290 this.$input
.attr( 'placeholder', config
.placeholder
);
15292 if ( config
.maxLength
!== undefined ) {
15293 this.$input
.attr( 'maxlength', config
.maxLength
);
15295 if ( config
.autofocus
) {
15296 this.$input
.attr( 'autofocus', 'autofocus' );
15298 if ( config
.required
) {
15299 this.$input
.attr( 'required', 'required' );
15300 this.$input
.attr( 'aria-required', 'true' );
15302 if ( config
.autocomplete
=== false ) {
15303 this.$input
.attr( 'autocomplete', 'off' );
15305 if ( this.multiline
&& config
.rows
) {
15306 this.$input
.attr( 'rows', config
.rows
);
15308 if ( this.label
|| config
.autosize
) {
15309 this.installParentChangeDetector();
15315 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
15316 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
15317 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
15318 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
15319 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
15321 /* Static Properties */
15323 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
15331 * An `enter` event is emitted when the user presses 'enter' inside the text box.
15333 * Not emitted if the input is multiline.
15341 * Handle icon mouse down events.
15344 * @param {jQuery.Event} e Mouse down event
15347 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
15348 if ( e
.which
=== 1 ) {
15349 this.$input
[ 0 ].focus();
15355 * Handle indicator mouse down events.
15358 * @param {jQuery.Event} e Mouse down event
15361 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
15362 if ( e
.which
=== 1 ) {
15363 if ( this.type
=== 'search' ) {
15364 // Clear the text field
15365 this.setValue( '' );
15367 this.$input
[ 0 ].focus();
15373 * Handle key press events.
15376 * @param {jQuery.Event} e Key press event
15377 * @fires enter If enter key is pressed and input is not multiline
15379 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
15380 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
15381 this.emit( 'enter', e
);
15386 * Handle blur events.
15389 * @param {jQuery.Event} e Blur event
15391 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
15392 this.setValidityFlag();
15396 * Handle element attach events.
15399 * @param {jQuery.Event} e Element attach event
15401 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
15402 // Any previously calculated size is now probably invalid if we reattached elsewhere
15403 this.valCache
= null;
15405 this.positionLabel();
15409 * Handle change events.
15411 * @param {string} value
15414 OO
.ui
.TextInputWidget
.prototype.onChange = function () {
15415 this.updateSearchIndicator();
15416 this.setValidityFlag();
15421 * Handle disable events.
15423 * @param {boolean} disabled Element is disabled
15426 OO
.ui
.TextInputWidget
.prototype.onDisable = function () {
15427 this.updateSearchIndicator();
15431 * Check if the input is {@link #readOnly read-only}.
15433 * @return {boolean}
15435 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
15436 return this.readOnly
;
15440 * Set the {@link #readOnly read-only} state of the input.
15442 * @param {boolean} state Make input read-only
15445 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
15446 this.readOnly
= !!state
;
15447 this.$input
.prop( 'readOnly', this.readOnly
);
15448 this.updateSearchIndicator();
15453 * Support function for making #onElementAttach work across browsers.
15455 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
15456 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
15458 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
15459 * first time that the element gets attached to the documented.
15461 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
15462 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
15463 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
15466 if ( MutationObserver
) {
15467 // The new way. If only it wasn't so ugly.
15469 if ( this.$element
.closest( 'html' ).length
) {
15470 // Widget is attached already, do nothing. This breaks the functionality of this function when
15471 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
15472 // would require observation of the whole document, which would hurt performance of other,
15473 // more important code.
15477 // Find topmost node in the tree
15478 topmostNode
= this.$element
[ 0 ];
15479 while ( topmostNode
.parentNode
) {
15480 topmostNode
= topmostNode
.parentNode
;
15483 // We have no way to detect the $element being attached somewhere without observing the entire
15484 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
15485 // parent node of $element, and instead detect when $element is removed from it (and thus
15486 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
15487 // doesn't get attached, we end up back here and create the parent.
15489 mutationObserver
= new MutationObserver( function ( mutations
) {
15490 var i
, j
, removedNodes
;
15491 for ( i
= 0; i
< mutations
.length
; i
++ ) {
15492 removedNodes
= mutations
[ i
].removedNodes
;
15493 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
15494 if ( removedNodes
[ j
] === topmostNode
) {
15495 setTimeout( onRemove
, 0 );
15502 onRemove = function () {
15503 // If the node was attached somewhere else, report it
15504 if ( widget
.$element
.closest( 'html' ).length
) {
15505 widget
.onElementAttach();
15507 mutationObserver
.disconnect();
15508 widget
.installParentChangeDetector();
15511 // Create a fake parent and observe it
15512 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
15513 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
15515 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
15516 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
15517 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
15522 * Automatically adjust the size of the text input.
15524 * This only affects #multiline inputs that are {@link #autosize autosized}.
15528 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
15529 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
, idealHeight
;
15531 if ( this.multiline
&& this.autosize
&& this.$input
.val() !== this.valCache
) {
15533 .val( this.$input
.val() )
15534 .attr( 'rows', this.minRows
)
15535 // Set inline height property to 0 to measure scroll height
15536 .css( 'height', 0 );
15538 this.$clone
.removeClass( 'oo-ui-element-hidden' );
15540 this.valCache
= this.$input
.val();
15542 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
15544 // Remove inline height property to measure natural heights
15545 this.$clone
.css( 'height', '' );
15546 innerHeight
= this.$clone
.innerHeight();
15547 outerHeight
= this.$clone
.outerHeight();
15549 // Measure max rows height
15551 .attr( 'rows', this.maxRows
)
15552 .css( 'height', 'auto' )
15554 maxInnerHeight
= this.$clone
.innerHeight();
15556 // Difference between reported innerHeight and scrollHeight with no scrollbars present
15557 // Equals 1 on Blink-based browsers and 0 everywhere else
15558 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
15559 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
15561 this.$clone
.addClass( 'oo-ui-element-hidden' );
15563 // Only apply inline height when expansion beyond natural height is needed
15564 if ( idealHeight
> innerHeight
) {
15565 // Use the difference between the inner and outer height as a buffer
15566 this.$input
.css( 'height', idealHeight
+ ( outerHeight
- innerHeight
) );
15568 this.$input
.css( 'height', '' );
15578 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
15579 return config
.multiline
?
15580 $( '<textarea>' ) :
15581 $( '<input type="' + this.getSaneType( config
) + '" />' );
15585 * Get sanitized value for 'type' for given config.
15587 * @param {Object} config Configuration options
15588 * @return {string|null}
15591 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
15592 var type
= [ 'text', 'password', 'search', 'email', 'url' ].indexOf( config
.type
) !== -1 ?
15595 return config
.multiline
? 'multiline' : type
;
15599 * Check if the input supports multiple lines.
15601 * @return {boolean}
15603 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
15604 return !!this.multiline
;
15608 * Check if the input automatically adjusts its size.
15610 * @return {boolean}
15612 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
15613 return !!this.autosize
;
15617 * Select the entire text of the input.
15621 OO
.ui
.TextInputWidget
.prototype.select = function () {
15622 this.$input
.select();
15627 * Focus the input and move the cursor to the end.
15629 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
15631 element
= this.$input
[ 0 ];
15633 if ( element
.selectionStart
!== undefined ) {
15634 element
.selectionStart
= element
.selectionEnd
= element
.value
.length
;
15635 } else if ( element
.createTextRange
) {
15637 textRange
= element
.createTextRange();
15638 textRange
.collapse( false );
15639 textRange
.select();
15644 * Set the validation pattern.
15646 * The validation pattern is either a regular expression, a function, or the symbolic name of a
15647 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
15648 * value must contain only numbers).
15650 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
15651 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
15653 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
15654 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
15655 this.validate
= validate
;
15657 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
15662 * Sets the 'invalid' flag appropriately.
15664 * @param {boolean} [isValid] Optionally override validation result
15666 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
15668 setFlag = function ( valid
) {
15670 widget
.$input
.attr( 'aria-invalid', 'true' );
15672 widget
.$input
.removeAttr( 'aria-invalid' );
15674 widget
.setFlags( { invalid
: !valid
} );
15677 if ( isValid
!== undefined ) {
15678 setFlag( isValid
);
15680 this.getValidity().then( function () {
15689 * Check if a value is valid.
15691 * This method returns a promise that resolves with a boolean `true` if the current value is
15692 * considered valid according to the supplied {@link #validate validation pattern}.
15695 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
15697 OO
.ui
.TextInputWidget
.prototype.isValid = function () {
15700 if ( this.validate
instanceof Function
) {
15701 result
= this.validate( this.getValue() );
15702 if ( $.isFunction( result
.promise
) ) {
15703 return result
.promise();
15705 return $.Deferred().resolve( !!result
).promise();
15708 return $.Deferred().resolve( !!this.getValue().match( this.validate
) ).promise();
15713 * Get the validity of current value.
15715 * This method returns a promise that resolves if the value is valid and rejects if
15716 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
15718 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
15720 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
15721 var result
, promise
;
15723 function rejectOrResolve( valid
) {
15725 return $.Deferred().resolve().promise();
15727 return $.Deferred().reject().promise();
15731 if ( this.validate
instanceof Function
) {
15732 result
= this.validate( this.getValue() );
15734 if ( $.isFunction( result
.promise
) ) {
15735 promise
= $.Deferred();
15737 result
.then( function ( valid
) {
15747 return promise
.promise();
15749 return rejectOrResolve( result
);
15752 return rejectOrResolve( this.getValue().match( this.validate
) );
15757 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
15759 * @param {string} labelPosition Label position, 'before' or 'after'
15762 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
15763 this.labelPosition
= labelPosition
;
15764 this.updatePosition();
15769 * Deprecated alias of #setLabelPosition
15771 * @deprecated Use setLabelPosition instead.
15773 OO
.ui
.TextInputWidget
.prototype.setPosition
=
15774 OO
.ui
.TextInputWidget
.prototype.setLabelPosition
;
15777 * Update the position of the inline label.
15779 * This method is called by #setLabelPosition, and can also be called on its own if
15780 * something causes the label to be mispositioned.
15784 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
15785 var after
= this.labelPosition
=== 'after';
15788 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
15789 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
15791 this.positionLabel();
15797 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
15798 * already empty or when it's not editable.
15800 OO
.ui
.TextInputWidget
.prototype.updateSearchIndicator = function () {
15801 if ( this.type
=== 'search' ) {
15802 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
15803 this.setIndicator( null );
15805 this.setIndicator( 'clear' );
15811 * Position the label by setting the correct padding on the input.
15816 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
15817 var after
, rtl
, property
;
15818 // Clear old values
15820 // Clear old values if present
15822 'padding-right': '',
15826 if ( this.label
) {
15827 this.$element
.append( this.$label
);
15829 this.$label
.detach();
15833 after
= this.labelPosition
=== 'after';
15834 rtl
= this.$element
.css( 'direction' ) === 'rtl';
15835 property
= after
=== rtl
? 'padding-left' : 'padding-right';
15837 this.$input
.css( property
, this.$label
.outerWidth( true ) );
15845 OO
.ui
.TextInputWidget
.prototype.gatherPreInfuseState = function ( node
) {
15847 state
= OO
.ui
.TextInputWidget
.parent
.prototype.gatherPreInfuseState
.call( this, node
),
15848 $input
= $( node
).find( '.oo-ui-inputWidget-input' );
15849 state
.$input
= $input
; // shortcut for performance, used in InputWidget
15850 if ( this.multiline
) {
15851 state
.scrollTop
= $input
.scrollTop();
15859 OO
.ui
.TextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
15860 OO
.ui
.TextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
15861 if ( state
.scrollTop
!== undefined ) {
15862 this.$input
.scrollTop( state
.scrollTop
);
15867 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
15868 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
15869 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
15871 * - by typing a value in the text input field. If the value exactly matches the value of a menu
15872 * option, that option will appear to be selected.
15873 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
15876 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
15879 * // Example: A ComboBoxWidget.
15880 * var comboBox = new OO.ui.ComboBoxWidget( {
15881 * label: 'ComboBoxWidget',
15882 * input: { value: 'Option One' },
15885 * new OO.ui.MenuOptionWidget( {
15886 * data: 'Option 1',
15887 * label: 'Option One'
15889 * new OO.ui.MenuOptionWidget( {
15890 * data: 'Option 2',
15891 * label: 'Option Two'
15893 * new OO.ui.MenuOptionWidget( {
15894 * data: 'Option 3',
15895 * label: 'Option Three'
15897 * new OO.ui.MenuOptionWidget( {
15898 * data: 'Option 4',
15899 * label: 'Option Four'
15901 * new OO.ui.MenuOptionWidget( {
15902 * data: 'Option 5',
15903 * label: 'Option Five'
15908 * $( 'body' ).append( comboBox.$element );
15910 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
15913 * @extends OO.ui.Widget
15914 * @mixins OO.ui.mixin.TabIndexedElement
15917 * @param {Object} [config] Configuration options
15918 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
15919 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
15920 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
15921 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
15922 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
15924 OO
.ui
.ComboBoxWidget
= function OoUiComboBoxWidget( config
) {
15925 // Configuration initialization
15926 config
= config
|| {};
15928 // Parent constructor
15929 OO
.ui
.ComboBoxWidget
.parent
.call( this, config
);
15931 // Properties (must be set before TabIndexedElement constructor call)
15932 this.$indicator
= this.$( '<span>' );
15934 // Mixin constructors
15935 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$indicator
} ) );
15938 this.$overlay
= config
.$overlay
|| this.$element
;
15939 this.input
= new OO
.ui
.TextInputWidget( $.extend(
15942 $indicator
: this.$indicator
,
15943 disabled
: this.isDisabled()
15947 this.input
.$input
.eq( 0 ).attr( {
15949 'aria-autocomplete': 'list'
15951 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
15955 $container
: this.input
.$element
,
15956 disabled
: this.isDisabled()
15962 this.$indicator
.on( {
15963 click
: this.onClick
.bind( this ),
15964 keypress
: this.onKeyPress
.bind( this )
15966 this.input
.connect( this, {
15967 change
: 'onInputChange',
15968 enter
: 'onInputEnter'
15970 this.menu
.connect( this, {
15971 choose
: 'onMenuChoose',
15972 add
: 'onMenuItemsChange',
15973 remove
: 'onMenuItemsChange'
15977 this.$element
.addClass( 'oo-ui-comboBoxWidget' ).append( this.input
.$element
);
15978 this.$overlay
.append( this.menu
.$element
);
15979 this.onMenuItemsChange();
15984 OO
.inheritClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.Widget
);
15985 OO
.mixinClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.mixin
.TabIndexedElement
);
15990 * Get the combobox's menu.
15991 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
15993 OO
.ui
.ComboBoxWidget
.prototype.getMenu = function () {
15998 * Get the combobox's text input widget.
15999 * @return {OO.ui.TextInputWidget} Text input widget
16001 OO
.ui
.ComboBoxWidget
.prototype.getInput = function () {
16006 * Handle input change events.
16009 * @param {string} value New value
16011 OO
.ui
.ComboBoxWidget
.prototype.onInputChange = function ( value
) {
16012 var match
= this.menu
.getItemFromData( value
);
16014 this.menu
.selectItem( match
);
16015 if ( this.menu
.getHighlightedItem() ) {
16016 this.menu
.highlightItem( match
);
16019 if ( !this.isDisabled() ) {
16020 this.menu
.toggle( true );
16025 * Handle mouse click events.
16029 * @param {jQuery.Event} e Mouse click event
16031 OO
.ui
.ComboBoxWidget
.prototype.onClick = function ( e
) {
16032 if ( !this.isDisabled() && e
.which
=== 1 ) {
16033 this.menu
.toggle();
16034 this.input
.$input
[ 0 ].focus();
16040 * Handle key press events.
16044 * @param {jQuery.Event} e Key press event
16046 OO
.ui
.ComboBoxWidget
.prototype.onKeyPress = function ( e
) {
16047 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
16048 this.menu
.toggle();
16049 this.input
.$input
[ 0 ].focus();
16055 * Handle input enter events.
16059 OO
.ui
.ComboBoxWidget
.prototype.onInputEnter = function () {
16060 if ( !this.isDisabled() ) {
16061 this.menu
.toggle( false );
16066 * Handle menu choose events.
16069 * @param {OO.ui.OptionWidget} item Chosen item
16071 OO
.ui
.ComboBoxWidget
.prototype.onMenuChoose = function ( item
) {
16072 this.input
.setValue( item
.getData() );
16076 * Handle menu item change events.
16080 OO
.ui
.ComboBoxWidget
.prototype.onMenuItemsChange = function () {
16081 var match
= this.menu
.getItemFromData( this.input
.getValue() );
16082 this.menu
.selectItem( match
);
16083 if ( this.menu
.getHighlightedItem() ) {
16084 this.menu
.highlightItem( match
);
16086 this.$element
.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu
.isEmpty() );
16092 OO
.ui
.ComboBoxWidget
.prototype.setDisabled = function ( disabled
) {
16094 OO
.ui
.ComboBoxWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
16096 if ( this.input
) {
16097 this.input
.setDisabled( this.isDisabled() );
16100 this.menu
.setDisabled( this.isDisabled() );
16107 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
16108 * be configured with a `label` option that is set to a string, a label node, or a function:
16110 * - String: a plaintext string
16111 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
16112 * label that includes a link or special styling, such as a gray color or additional graphical elements.
16113 * - Function: a function that will produce a string in the future. Functions are used
16114 * in cases where the value of the label is not currently defined.
16116 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
16117 * will come into focus when the label is clicked.
16120 * // Examples of LabelWidgets
16121 * var label1 = new OO.ui.LabelWidget( {
16122 * label: 'plaintext label'
16124 * var label2 = new OO.ui.LabelWidget( {
16125 * label: $( '<a href="default.html">jQuery label</a>' )
16127 * // Create a fieldset layout with fields for each example
16128 * var fieldset = new OO.ui.FieldsetLayout();
16129 * fieldset.addItems( [
16130 * new OO.ui.FieldLayout( label1 ),
16131 * new OO.ui.FieldLayout( label2 )
16133 * $( 'body' ).append( fieldset.$element );
16137 * @extends OO.ui.Widget
16138 * @mixins OO.ui.mixin.LabelElement
16141 * @param {Object} [config] Configuration options
16142 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
16143 * Clicking the label will focus the specified input field.
16145 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
16146 // Configuration initialization
16147 config
= config
|| {};
16149 // Parent constructor
16150 OO
.ui
.LabelWidget
.parent
.call( this, config
);
16152 // Mixin constructors
16153 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
16154 OO
.ui
.mixin
.TitledElement
.call( this, config
);
16157 this.input
= config
.input
;
16160 if ( this.input
instanceof OO
.ui
.InputWidget
) {
16161 this.$element
.on( 'click', this.onClick
.bind( this ) );
16165 this.$element
.addClass( 'oo-ui-labelWidget' );
16170 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
16171 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
16172 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
16174 /* Static Properties */
16176 OO
.ui
.LabelWidget
.static.tagName
= 'span';
16181 * Handles label mouse click events.
16184 * @param {jQuery.Event} e Mouse click event
16186 OO
.ui
.LabelWidget
.prototype.onClick = function () {
16187 this.input
.simulateLabelClick();
16192 * OptionWidgets are special elements that can be selected and configured with data. The
16193 * data is often unique for each option, but it does not have to be. OptionWidgets are used
16194 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
16195 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
16197 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16200 * @extends OO.ui.Widget
16201 * @mixins OO.ui.mixin.LabelElement
16202 * @mixins OO.ui.mixin.FlaggedElement
16205 * @param {Object} [config] Configuration options
16207 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
16208 // Configuration initialization
16209 config
= config
|| {};
16211 // Parent constructor
16212 OO
.ui
.OptionWidget
.parent
.call( this, config
);
16214 // Mixin constructors
16215 OO
.ui
.mixin
.ItemWidget
.call( this );
16216 OO
.ui
.mixin
.LabelElement
.call( this, config
);
16217 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
16220 this.selected
= false;
16221 this.highlighted
= false;
16222 this.pressed
= false;
16226 .data( 'oo-ui-optionWidget', this )
16227 .attr( 'role', 'option' )
16228 .attr( 'aria-selected', 'false' )
16229 .addClass( 'oo-ui-optionWidget' )
16230 .append( this.$label
);
16235 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
16236 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
16237 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
16238 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
16240 /* Static Properties */
16242 OO
.ui
.OptionWidget
.static.selectable
= true;
16244 OO
.ui
.OptionWidget
.static.highlightable
= true;
16246 OO
.ui
.OptionWidget
.static.pressable
= true;
16248 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
16253 * Check if the option can be selected.
16255 * @return {boolean} Item is selectable
16257 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
16258 return this.constructor.static.selectable
&& !this.isDisabled() && this.isVisible();
16262 * Check if the option can be highlighted. A highlight indicates that the option
16263 * may be selected when a user presses enter or clicks. Disabled items cannot
16266 * @return {boolean} Item is highlightable
16268 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
16269 return this.constructor.static.highlightable
&& !this.isDisabled() && this.isVisible();
16273 * Check if the option can be pressed. The pressed state occurs when a user mouses
16274 * down on an item, but has not yet let go of the mouse.
16276 * @return {boolean} Item is pressable
16278 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
16279 return this.constructor.static.pressable
&& !this.isDisabled() && this.isVisible();
16283 * Check if the option is selected.
16285 * @return {boolean} Item is selected
16287 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
16288 return this.selected
;
16292 * Check if the option is highlighted. A highlight indicates that the
16293 * item may be selected when a user presses enter or clicks.
16295 * @return {boolean} Item is highlighted
16297 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
16298 return this.highlighted
;
16302 * Check if the option is pressed. The pressed state occurs when a user mouses
16303 * down on an item, but has not yet let go of the mouse. The item may appear
16304 * selected, but it will not be selected until the user releases the mouse.
16306 * @return {boolean} Item is pressed
16308 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
16309 return this.pressed
;
16313 * Set the option’s selected state. In general, all modifications to the selection
16314 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
16315 * method instead of this method.
16317 * @param {boolean} [state=false] Select option
16320 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
16321 if ( this.constructor.static.selectable
) {
16322 this.selected
= !!state
;
16324 .toggleClass( 'oo-ui-optionWidget-selected', state
)
16325 .attr( 'aria-selected', state
.toString() );
16326 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
16327 this.scrollElementIntoView();
16329 this.updateThemeClasses();
16335 * Set the option’s highlighted state. In general, all programmatic
16336 * modifications to the highlight should be handled by the
16337 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
16338 * method instead of this method.
16340 * @param {boolean} [state=false] Highlight option
16343 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
16344 if ( this.constructor.static.highlightable
) {
16345 this.highlighted
= !!state
;
16346 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
16347 this.updateThemeClasses();
16353 * Set the option’s pressed state. In general, all
16354 * programmatic modifications to the pressed state should be handled by the
16355 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
16356 * method instead of this method.
16358 * @param {boolean} [state=false] Press option
16361 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
16362 if ( this.constructor.static.pressable
) {
16363 this.pressed
= !!state
;
16364 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
16365 this.updateThemeClasses();
16371 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
16372 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
16373 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
16374 * options. For more information about options and selects, please see the
16375 * [OOjs UI documentation on MediaWiki][1].
16378 * // Decorated options in a select widget
16379 * var select = new OO.ui.SelectWidget( {
16381 * new OO.ui.DecoratedOptionWidget( {
16383 * label: 'Option with icon',
16386 * new OO.ui.DecoratedOptionWidget( {
16388 * label: 'Option with indicator',
16389 * indicator: 'next'
16393 * $( 'body' ).append( select.$element );
16395 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16398 * @extends OO.ui.OptionWidget
16399 * @mixins OO.ui.mixin.IconElement
16400 * @mixins OO.ui.mixin.IndicatorElement
16403 * @param {Object} [config] Configuration options
16405 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
16406 // Parent constructor
16407 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
16409 // Mixin constructors
16410 OO
.ui
.mixin
.IconElement
.call( this, config
);
16411 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
16415 .addClass( 'oo-ui-decoratedOptionWidget' )
16416 .prepend( this.$icon
)
16417 .append( this.$indicator
);
16422 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
16423 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
16424 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
16427 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
16428 * can be selected and configured with data. The class is
16429 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
16430 * [OOjs UI documentation on MediaWiki] [1] for more information.
16432 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
16435 * @extends OO.ui.DecoratedOptionWidget
16436 * @mixins OO.ui.mixin.ButtonElement
16437 * @mixins OO.ui.mixin.TabIndexedElement
16438 * @mixins OO.ui.mixin.TitledElement
16441 * @param {Object} [config] Configuration options
16443 OO
.ui
.ButtonOptionWidget
= function OoUiButtonOptionWidget( config
) {
16444 // Configuration initialization
16445 config
= config
|| {};
16447 // Parent constructor
16448 OO
.ui
.ButtonOptionWidget
.parent
.call( this, config
);
16450 // Mixin constructors
16451 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
16452 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
16453 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, {
16454 $tabIndexed
: this.$button
,
16459 this.$element
.addClass( 'oo-ui-buttonOptionWidget' );
16460 this.$button
.append( this.$element
.contents() );
16461 this.$element
.append( this.$button
);
16466 OO
.inheritClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
16467 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.ButtonElement
);
16468 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.TitledElement
);
16469 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.TabIndexedElement
);
16471 /* Static Properties */
16473 // Allow button mouse down events to pass through so they can be handled by the parent select widget
16474 OO
.ui
.ButtonOptionWidget
.static.cancelButtonMouseDownEvents
= false;
16476 OO
.ui
.ButtonOptionWidget
.static.highlightable
= false;
16483 OO
.ui
.ButtonOptionWidget
.prototype.setSelected = function ( state
) {
16484 OO
.ui
.ButtonOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
16486 if ( this.constructor.static.selectable
) {
16487 this.setActive( state
);
16494 * RadioOptionWidget is an option widget that looks like a radio button.
16495 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
16496 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
16498 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
16501 * @extends OO.ui.OptionWidget
16504 * @param {Object} [config] Configuration options
16506 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
16507 // Configuration initialization
16508 config
= config
|| {};
16510 // Properties (must be done before parent constructor which calls #setDisabled)
16511 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
16513 // Parent constructor
16514 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
16517 this.radio
.$input
.on( 'focus', this.onInputFocus
.bind( this ) );
16520 // Remove implicit role, we're handling it ourselves
16521 this.radio
.$input
.attr( 'role', 'presentation' );
16523 .addClass( 'oo-ui-radioOptionWidget' )
16524 .attr( 'role', 'radio' )
16525 .attr( 'aria-checked', 'false' )
16526 .removeAttr( 'aria-selected' )
16527 .prepend( this.radio
.$element
);
16532 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
16534 /* Static Properties */
16536 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
16538 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
16540 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
16542 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
16547 * @param {jQuery.Event} e Focus event
16550 OO
.ui
.RadioOptionWidget
.prototype.onInputFocus = function () {
16551 this.radio
.$input
.blur();
16552 this.$element
.parent().focus();
16558 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
16559 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
16561 this.radio
.setSelected( state
);
16563 .attr( 'aria-checked', state
.toString() )
16564 .removeAttr( 'aria-selected' );
16572 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
16573 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
16575 this.radio
.setDisabled( this.isDisabled() );
16581 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
16582 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
16583 * the [OOjs UI documentation on MediaWiki] [1] for more information.
16585 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16588 * @extends OO.ui.DecoratedOptionWidget
16591 * @param {Object} [config] Configuration options
16593 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
16594 // Configuration initialization
16595 config
= $.extend( { icon
: 'check' }, config
);
16597 // Parent constructor
16598 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
16602 .attr( 'role', 'menuitem' )
16603 .addClass( 'oo-ui-menuOptionWidget' );
16608 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
16610 /* Static Properties */
16612 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
16615 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
16616 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
16619 * var myDropdown = new OO.ui.DropdownWidget( {
16622 * new OO.ui.MenuSectionOptionWidget( {
16625 * new OO.ui.MenuOptionWidget( {
16627 * label: 'Welsh Corgi'
16629 * new OO.ui.MenuOptionWidget( {
16631 * label: 'Standard Poodle'
16633 * new OO.ui.MenuSectionOptionWidget( {
16636 * new OO.ui.MenuOptionWidget( {
16643 * $( 'body' ).append( myDropdown.$element );
16647 * @extends OO.ui.DecoratedOptionWidget
16650 * @param {Object} [config] Configuration options
16652 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
16653 // Parent constructor
16654 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
16657 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' );
16662 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
16664 /* Static Properties */
16666 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
16668 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
16671 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
16673 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
16674 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
16678 * @extends OO.ui.DecoratedOptionWidget
16681 * @param {Object} [config] Configuration options
16682 * @cfg {number} [level] Indentation level
16683 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
16685 OO
.ui
.OutlineOptionWidget
= function OoUiOutlineOptionWidget( config
) {
16686 // Configuration initialization
16687 config
= config
|| {};
16689 // Parent constructor
16690 OO
.ui
.OutlineOptionWidget
.parent
.call( this, config
);
16694 this.movable
= !!config
.movable
;
16695 this.removable
= !!config
.removable
;
16698 this.$element
.addClass( 'oo-ui-outlineOptionWidget' );
16699 this.setLevel( config
.level
);
16704 OO
.inheritClass( OO
.ui
.OutlineOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
16706 /* Static Properties */
16708 OO
.ui
.OutlineOptionWidget
.static.highlightable
= false;
16710 OO
.ui
.OutlineOptionWidget
.static.scrollIntoViewOnSelect
= true;
16712 OO
.ui
.OutlineOptionWidget
.static.levelClass
= 'oo-ui-outlineOptionWidget-level-';
16714 OO
.ui
.OutlineOptionWidget
.static.levels
= 3;
16719 * Check if item is movable.
16721 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16723 * @return {boolean} Item is movable
16725 OO
.ui
.OutlineOptionWidget
.prototype.isMovable = function () {
16726 return this.movable
;
16730 * Check if item is removable.
16732 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16734 * @return {boolean} Item is removable
16736 OO
.ui
.OutlineOptionWidget
.prototype.isRemovable = function () {
16737 return this.removable
;
16741 * Get indentation level.
16743 * @return {number} Indentation level
16745 OO
.ui
.OutlineOptionWidget
.prototype.getLevel = function () {
16752 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16754 * @param {boolean} movable Item is movable
16757 OO
.ui
.OutlineOptionWidget
.prototype.setMovable = function ( movable
) {
16758 this.movable
= !!movable
;
16759 this.updateThemeClasses();
16764 * Set removability.
16766 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16768 * @param {boolean} movable Item is removable
16771 OO
.ui
.OutlineOptionWidget
.prototype.setRemovable = function ( removable
) {
16772 this.removable
= !!removable
;
16773 this.updateThemeClasses();
16778 * Set indentation level.
16780 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
16783 OO
.ui
.OutlineOptionWidget
.prototype.setLevel = function ( level
) {
16784 var levels
= this.constructor.static.levels
,
16785 levelClass
= this.constructor.static.levelClass
,
16788 this.level
= level
? Math
.max( 0, Math
.min( levels
- 1, level
) ) : 0;
16790 if ( this.level
=== i
) {
16791 this.$element
.addClass( levelClass
+ i
);
16793 this.$element
.removeClass( levelClass
+ i
);
16796 this.updateThemeClasses();
16802 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
16804 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
16805 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
16809 * @extends OO.ui.OptionWidget
16812 * @param {Object} [config] Configuration options
16814 OO
.ui
.TabOptionWidget
= function OoUiTabOptionWidget( config
) {
16815 // Configuration initialization
16816 config
= config
|| {};
16818 // Parent constructor
16819 OO
.ui
.TabOptionWidget
.parent
.call( this, config
);
16822 this.$element
.addClass( 'oo-ui-tabOptionWidget' );
16827 OO
.inheritClass( OO
.ui
.TabOptionWidget
, OO
.ui
.OptionWidget
);
16829 /* Static Properties */
16831 OO
.ui
.TabOptionWidget
.static.highlightable
= false;
16834 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
16835 * By default, each popup has an anchor that points toward its origin.
16836 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
16839 * // A popup widget.
16840 * var popup = new OO.ui.PopupWidget( {
16841 * $content: $( '<p>Hi there!</p>' ),
16846 * $( 'body' ).append( popup.$element );
16847 * // To display the popup, toggle the visibility to 'true'.
16848 * popup.toggle( true );
16850 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
16853 * @extends OO.ui.Widget
16854 * @mixins OO.ui.mixin.LabelElement
16857 * @param {Object} [config] Configuration options
16858 * @cfg {number} [width=320] Width of popup in pixels
16859 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
16860 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
16861 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
16862 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
16863 * popup is leaning towards the right of the screen.
16864 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
16865 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
16866 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
16867 * sentence in the given language.
16868 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
16869 * See the [OOjs UI docs on MediaWiki][3] for an example.
16870 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
16871 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
16872 * @cfg {jQuery} [$content] Content to append to the popup's body
16873 * @cfg {jQuery} [$footer] Content to append to the popup's footer
16874 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
16875 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
16876 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
16878 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
16879 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
16881 * @cfg {boolean} [padded] Add padding to the popup's body
16883 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
16884 // Configuration initialization
16885 config
= config
|| {};
16887 // Parent constructor
16888 OO
.ui
.PopupWidget
.parent
.call( this, config
);
16890 // Properties (must be set before ClippableElement constructor call)
16891 this.$body
= $( '<div>' );
16892 this.$popup
= $( '<div>' );
16894 // Mixin constructors
16895 OO
.ui
.mixin
.LabelElement
.call( this, config
);
16896 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, {
16897 $clippable
: this.$body
,
16898 $clippableContainer
: this.$popup
16902 this.$head
= $( '<div>' );
16903 this.$footer
= $( '<div>' );
16904 this.$anchor
= $( '<div>' );
16905 // If undefined, will be computed lazily in updateDimensions()
16906 this.$container
= config
.$container
;
16907 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
16908 this.autoClose
= !!config
.autoClose
;
16909 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
16910 this.transitionTimeout
= null;
16911 this.anchor
= null;
16912 this.width
= config
.width
!== undefined ? config
.width
: 320;
16913 this.height
= config
.height
!== undefined ? config
.height
: null;
16914 this.setAlignment( config
.align
);
16915 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
16916 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
16917 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
16920 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
16923 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
16924 this.$body
.addClass( 'oo-ui-popupWidget-body' );
16925 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
16927 .addClass( 'oo-ui-popupWidget-head' )
16928 .append( this.$label
, this.closeButton
.$element
);
16929 this.$footer
.addClass( 'oo-ui-popupWidget-footer' );
16930 if ( !config
.head
) {
16931 this.$head
.addClass( 'oo-ui-element-hidden' );
16933 if ( !config
.$footer
) {
16934 this.$footer
.addClass( 'oo-ui-element-hidden' );
16937 .addClass( 'oo-ui-popupWidget-popup' )
16938 .append( this.$head
, this.$body
, this.$footer
);
16940 .addClass( 'oo-ui-popupWidget' )
16941 .append( this.$popup
, this.$anchor
);
16942 // Move content, which was added to #$element by OO.ui.Widget, to the body
16943 if ( config
.$content
instanceof jQuery
) {
16944 this.$body
.append( config
.$content
);
16946 if ( config
.$footer
instanceof jQuery
) {
16947 this.$footer
.append( config
.$footer
);
16949 if ( config
.padded
) {
16950 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
16953 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
16954 // that reference properties not initialized at that time of parent class construction
16955 // TODO: Find a better way to handle post-constructor setup
16956 this.visible
= false;
16957 this.$element
.addClass( 'oo-ui-element-hidden' );
16962 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
16963 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
16964 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
16969 * Handles mouse down events.
16972 * @param {MouseEvent} e Mouse down event
16974 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
16976 this.isVisible() &&
16977 !$.contains( this.$element
[ 0 ], e
.target
) &&
16978 ( !this.$autoCloseIgnore
|| !this.$autoCloseIgnore
.has( e
.target
).length
)
16980 this.toggle( false );
16985 * Bind mouse down listener.
16989 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
16990 // Capture clicks outside popup
16991 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler
);
16995 * Handles close button click events.
16999 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
17000 if ( this.isVisible() ) {
17001 this.toggle( false );
17006 * Unbind mouse down listener.
17010 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
17011 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler
);
17015 * Handles key down events.
17018 * @param {KeyboardEvent} e Key down event
17020 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
17022 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
17025 this.toggle( false );
17026 e
.preventDefault();
17027 e
.stopPropagation();
17032 * Bind key down listener.
17036 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
17037 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler
);
17041 * Unbind key down listener.
17045 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
17046 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler
);
17050 * Show, hide, or toggle the visibility of the anchor.
17052 * @param {boolean} [show] Show anchor, omit to toggle
17054 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
17055 show
= show
=== undefined ? !this.anchored
: !!show
;
17057 if ( this.anchored
!== show
) {
17059 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
17061 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
17063 this.anchored
= show
;
17068 * Check if the anchor is visible.
17070 * @return {boolean} Anchor is visible
17072 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
17073 return this.anchor
;
17079 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
17081 show
= show
=== undefined ? !this.isVisible() : !!show
;
17083 change
= show
!== this.isVisible();
17086 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
17090 if ( this.autoClose
) {
17091 this.bindMouseDownListener();
17092 this.bindKeyDownListener();
17094 this.updateDimensions();
17095 this.toggleClipping( true );
17097 this.toggleClipping( false );
17098 if ( this.autoClose
) {
17099 this.unbindMouseDownListener();
17100 this.unbindKeyDownListener();
17109 * Set the size of the popup.
17111 * Changing the size may also change the popup's position depending on the alignment.
17113 * @param {number} width Width in pixels
17114 * @param {number} height Height in pixels
17115 * @param {boolean} [transition=false] Use a smooth transition
17118 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
17119 this.width
= width
;
17120 this.height
= height
!== undefined ? height
: null;
17121 if ( this.isVisible() ) {
17122 this.updateDimensions( transition
);
17127 * Update the size and position.
17129 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
17130 * be called automatically.
17132 * @param {boolean} [transition=false] Use a smooth transition
17135 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
17136 var popupOffset
, originOffset
, containerLeft
, containerWidth
, containerRight
,
17137 popupLeft
, popupRight
, overlapLeft
, overlapRight
, anchorWidth
,
17138 align
= this.align
,
17141 if ( !this.$container
) {
17142 // Lazy-initialize $container if not specified in constructor
17143 this.$container
= $( this.getClosestScrollableElementContainer() );
17146 // Set height and width before measuring things, since it might cause our measurements
17147 // to change (e.g. due to scrollbars appearing or disappearing)
17150 height
: this.height
!== null ? this.height
: 'auto'
17153 // If we are in RTL, we need to flip the alignment, unless it is center
17154 if ( align
=== 'forwards' || align
=== 'backwards' ) {
17155 if ( this.$container
.css( 'direction' ) === 'rtl' ) {
17156 align
= ( { forwards
: 'force-left', backwards
: 'force-right' } )[ this.align
];
17158 align
= ( { forwards
: 'force-right', backwards
: 'force-left' } )[ this.align
];
17163 // Compute initial popupOffset based on alignment
17164 popupOffset
= this.width
* ( { 'force-left': -1, center
: -0.5, 'force-right': 0 } )[ align
];
17166 // Figure out if this will cause the popup to go beyond the edge of the container
17167 originOffset
= this.$element
.offset().left
;
17168 containerLeft
= this.$container
.offset().left
;
17169 containerWidth
= this.$container
.innerWidth();
17170 containerRight
= containerLeft
+ containerWidth
;
17171 popupLeft
= popupOffset
- this.containerPadding
;
17172 popupRight
= popupOffset
+ this.containerPadding
+ this.width
+ this.containerPadding
;
17173 overlapLeft
= ( originOffset
+ popupLeft
) - containerLeft
;
17174 overlapRight
= containerRight
- ( originOffset
+ popupRight
);
17176 // Adjust offset to make the popup not go beyond the edge, if needed
17177 if ( overlapRight
< 0 ) {
17178 popupOffset
+= overlapRight
;
17179 } else if ( overlapLeft
< 0 ) {
17180 popupOffset
-= overlapLeft
;
17183 // Adjust offset to avoid anchor being rendered too close to the edge
17184 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
17185 // TODO: Find a measurement that works for CSS anchors and image anchors
17186 anchorWidth
= this.$anchor
[ 0 ].scrollWidth
* 2;
17187 if ( popupOffset
+ this.width
< anchorWidth
) {
17188 popupOffset
= anchorWidth
- this.width
;
17189 } else if ( -popupOffset
< anchorWidth
) {
17190 popupOffset
= -anchorWidth
;
17193 // Prevent transition from being interrupted
17194 clearTimeout( this.transitionTimeout
);
17195 if ( transition
) {
17196 // Enable transition
17197 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
17200 // Position body relative to anchor
17201 this.$popup
.css( 'margin-left', popupOffset
);
17203 if ( transition
) {
17204 // Prevent transitioning after transition is complete
17205 this.transitionTimeout
= setTimeout( function () {
17206 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
17209 // Prevent transitioning immediately
17210 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
17213 // Reevaluate clipping state since we've relocated and resized the popup
17220 * Set popup alignment
17221 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17222 * `backwards` or `forwards`.
17224 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
17225 // Validate alignment and transform deprecated values
17226 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
17227 this.align
= { left
: 'force-right', right
: 'force-left' }[ align
] || align
;
17229 this.align
= 'center';
17234 * Get popup alignment
17235 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17236 * `backwards` or `forwards`.
17238 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
17243 * Progress bars visually display the status of an operation, such as a download,
17244 * and can be either determinate or indeterminate:
17246 * - **determinate** process bars show the percent of an operation that is complete.
17248 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
17249 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
17250 * not use percentages.
17252 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
17255 * // Examples of determinate and indeterminate progress bars.
17256 * var progressBar1 = new OO.ui.ProgressBarWidget( {
17259 * var progressBar2 = new OO.ui.ProgressBarWidget();
17261 * // Create a FieldsetLayout to layout progress bars
17262 * var fieldset = new OO.ui.FieldsetLayout;
17263 * fieldset.addItems( [
17264 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
17265 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
17267 * $( 'body' ).append( fieldset.$element );
17270 * @extends OO.ui.Widget
17273 * @param {Object} [config] Configuration options
17274 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
17275 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
17276 * By default, the progress bar is indeterminate.
17278 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
17279 // Configuration initialization
17280 config
= config
|| {};
17282 // Parent constructor
17283 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
17286 this.$bar
= $( '<div>' );
17287 this.progress
= null;
17290 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
17291 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
17294 role
: 'progressbar',
17295 'aria-valuemin': 0,
17296 'aria-valuemax': 100
17298 .addClass( 'oo-ui-progressBarWidget' )
17299 .append( this.$bar
);
17304 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
17306 /* Static Properties */
17308 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
17313 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
17315 * @return {number|boolean} Progress percent
17317 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
17318 return this.progress
;
17322 * Set the percent of the process completed or `false` for an indeterminate process.
17324 * @param {number|boolean} progress Progress percent or `false` for indeterminate
17326 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
17327 this.progress
= progress
;
17329 if ( progress
!== false ) {
17330 this.$bar
.css( 'width', this.progress
+ '%' );
17331 this.$element
.attr( 'aria-valuenow', this.progress
);
17333 this.$bar
.css( 'width', '' );
17334 this.$element
.removeAttr( 'aria-valuenow' );
17336 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress
);
17340 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
17341 * and a menu of search results, which is displayed beneath the query
17342 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
17343 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
17344 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
17346 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
17347 * the [OOjs UI demos][1] for an example.
17349 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
17352 * @extends OO.ui.Widget
17355 * @param {Object} [config] Configuration options
17356 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
17357 * @cfg {string} [value] Initial query value
17359 OO
.ui
.SearchWidget
= function OoUiSearchWidget( config
) {
17360 // Configuration initialization
17361 config
= config
|| {};
17363 // Parent constructor
17364 OO
.ui
.SearchWidget
.parent
.call( this, config
);
17367 this.query
= new OO
.ui
.TextInputWidget( {
17369 placeholder
: config
.placeholder
,
17370 value
: config
.value
17372 this.results
= new OO
.ui
.SelectWidget();
17373 this.$query
= $( '<div>' );
17374 this.$results
= $( '<div>' );
17377 this.query
.connect( this, {
17378 change
: 'onQueryChange',
17379 enter
: 'onQueryEnter'
17381 this.query
.$input
.on( 'keydown', this.onQueryKeydown
.bind( this ) );
17385 .addClass( 'oo-ui-searchWidget-query' )
17386 .append( this.query
.$element
);
17388 .addClass( 'oo-ui-searchWidget-results' )
17389 .append( this.results
.$element
);
17391 .addClass( 'oo-ui-searchWidget' )
17392 .append( this.$results
, this.$query
);
17397 OO
.inheritClass( OO
.ui
.SearchWidget
, OO
.ui
.Widget
);
17402 * Handle query key down events.
17405 * @param {jQuery.Event} e Key down event
17407 OO
.ui
.SearchWidget
.prototype.onQueryKeydown = function ( e
) {
17408 var highlightedItem
, nextItem
,
17409 dir
= e
.which
=== OO
.ui
.Keys
.DOWN
? 1 : ( e
.which
=== OO
.ui
.Keys
.UP
? -1 : 0 );
17412 highlightedItem
= this.results
.getHighlightedItem();
17413 if ( !highlightedItem
) {
17414 highlightedItem
= this.results
.getSelectedItem();
17416 nextItem
= this.results
.getRelativeSelectableItem( highlightedItem
, dir
);
17417 this.results
.highlightItem( nextItem
);
17418 nextItem
.scrollElementIntoView();
17423 * Handle select widget select events.
17425 * Clears existing results. Subclasses should repopulate items according to new query.
17428 * @param {string} value New value
17430 OO
.ui
.SearchWidget
.prototype.onQueryChange = function () {
17432 this.results
.clearItems();
17436 * Handle select widget enter key events.
17438 * Chooses highlighted item.
17441 * @param {string} value New value
17443 OO
.ui
.SearchWidget
.prototype.onQueryEnter = function () {
17445 this.results
.chooseItem( this.results
.getHighlightedItem() );
17449 * Get the query input.
17451 * @return {OO.ui.TextInputWidget} Query input
17453 OO
.ui
.SearchWidget
.prototype.getQuery = function () {
17458 * Get the search results menu.
17460 * @return {OO.ui.SelectWidget} Menu of search results
17462 OO
.ui
.SearchWidget
.prototype.getResults = function () {
17463 return this.results
;
17467 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
17468 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
17469 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
17472 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
17473 * information, please see the [OOjs UI documentation on MediaWiki][1].
17476 * // Example of a select widget with three options
17477 * var select = new OO.ui.SelectWidget( {
17479 * new OO.ui.OptionWidget( {
17481 * label: 'Option One',
17483 * new OO.ui.OptionWidget( {
17485 * label: 'Option Two',
17487 * new OO.ui.OptionWidget( {
17489 * label: 'Option Three',
17493 * $( 'body' ).append( select.$element );
17495 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17499 * @extends OO.ui.Widget
17500 * @mixins OO.ui.mixin.GroupWidget
17503 * @param {Object} [config] Configuration options
17504 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
17505 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
17506 * the [OOjs UI documentation on MediaWiki] [2] for examples.
17507 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17509 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
17510 // Configuration initialization
17511 config
= config
|| {};
17513 // Parent constructor
17514 OO
.ui
.SelectWidget
.parent
.call( this, config
);
17516 // Mixin constructors
17517 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
17520 this.pressed
= false;
17521 this.selecting
= null;
17522 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
17523 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
17524 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
17525 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
17526 this.keyPressBuffer
= '';
17527 this.keyPressBufferTimer
= null;
17530 this.connect( this, {
17533 this.$element
.on( {
17534 mousedown
: this.onMouseDown
.bind( this ),
17535 mouseover
: this.onMouseOver
.bind( this ),
17536 mouseleave
: this.onMouseLeave
.bind( this )
17541 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
17542 .attr( 'role', 'listbox' );
17543 if ( Array
.isArray( config
.items
) ) {
17544 this.addItems( config
.items
);
17550 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
17552 // Need to mixin base class as well
17553 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupElement
);
17554 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
17557 OO
.ui
.SelectWidget
.static.passAllFilter = function () {
17566 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
17568 * @param {OO.ui.OptionWidget|null} item Highlighted item
17574 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
17575 * pressed state of an option.
17577 * @param {OO.ui.OptionWidget|null} item Pressed item
17583 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
17585 * @param {OO.ui.OptionWidget|null} item Selected item
17590 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
17591 * @param {OO.ui.OptionWidget} item Chosen item
17597 * An `add` event is emitted when options are added to the select with the #addItems method.
17599 * @param {OO.ui.OptionWidget[]} items Added items
17600 * @param {number} index Index of insertion point
17606 * A `remove` event is emitted when options are removed from the select with the #clearItems
17607 * or #removeItems methods.
17609 * @param {OO.ui.OptionWidget[]} items Removed items
17615 * Handle mouse down events.
17618 * @param {jQuery.Event} e Mouse down event
17620 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
17623 if ( !this.isDisabled() && e
.which
=== 1 ) {
17624 this.togglePressed( true );
17625 item
= this.getTargetItem( e
);
17626 if ( item
&& item
.isSelectable() ) {
17627 this.pressItem( item
);
17628 this.selecting
= item
;
17629 OO
.ui
.addCaptureEventListener(
17630 this.getElementDocument(),
17632 this.onMouseUpHandler
17634 OO
.ui
.addCaptureEventListener(
17635 this.getElementDocument(),
17637 this.onMouseMoveHandler
17645 * Handle mouse up events.
17648 * @param {jQuery.Event} e Mouse up event
17650 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
17653 this.togglePressed( false );
17654 if ( !this.selecting
) {
17655 item
= this.getTargetItem( e
);
17656 if ( item
&& item
.isSelectable() ) {
17657 this.selecting
= item
;
17660 if ( !this.isDisabled() && e
.which
=== 1 && this.selecting
) {
17661 this.pressItem( null );
17662 this.chooseItem( this.selecting
);
17663 this.selecting
= null;
17666 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup',
17667 this.onMouseUpHandler
);
17668 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mousemove',
17669 this.onMouseMoveHandler
);
17675 * Handle mouse move events.
17678 * @param {jQuery.Event} e Mouse move event
17680 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
17683 if ( !this.isDisabled() && this.pressed
) {
17684 item
= this.getTargetItem( e
);
17685 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
17686 this.pressItem( item
);
17687 this.selecting
= item
;
17694 * Handle mouse over events.
17697 * @param {jQuery.Event} e Mouse over event
17699 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
17702 if ( !this.isDisabled() ) {
17703 item
= this.getTargetItem( e
);
17704 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
17710 * Handle mouse leave events.
17713 * @param {jQuery.Event} e Mouse over event
17715 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
17716 if ( !this.isDisabled() ) {
17717 this.highlightItem( null );
17723 * Handle key down events.
17726 * @param {jQuery.Event} e Key down event
17728 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
17731 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
17733 if ( !this.isDisabled() && this.isVisible() ) {
17734 switch ( e
.keyCode
) {
17735 case OO
.ui
.Keys
.ENTER
:
17736 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
17737 // Was only highlighted, now let's select it. No-op if already selected.
17738 this.chooseItem( currentItem
);
17742 case OO
.ui
.Keys
.UP
:
17743 case OO
.ui
.Keys
.LEFT
:
17744 this.clearKeyPressBuffer();
17745 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
17748 case OO
.ui
.Keys
.DOWN
:
17749 case OO
.ui
.Keys
.RIGHT
:
17750 this.clearKeyPressBuffer();
17751 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
17754 case OO
.ui
.Keys
.ESCAPE
:
17755 case OO
.ui
.Keys
.TAB
:
17756 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
17757 currentItem
.setHighlighted( false );
17759 this.unbindKeyDownListener();
17760 this.unbindKeyPressListener();
17761 // Don't prevent tabbing away / defocusing
17767 if ( nextItem
.constructor.static.highlightable
) {
17768 this.highlightItem( nextItem
);
17770 this.chooseItem( nextItem
);
17772 nextItem
.scrollElementIntoView();
17776 // Can't just return false, because e is not always a jQuery event
17777 e
.preventDefault();
17778 e
.stopPropagation();
17784 * Bind key down listener.
17788 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
17789 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler
);
17793 * Unbind key down listener.
17797 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
17798 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler
);
17802 * Clear the key-press buffer
17806 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
17807 if ( this.keyPressBufferTimer
) {
17808 clearTimeout( this.keyPressBufferTimer
);
17809 this.keyPressBufferTimer
= null;
17811 this.keyPressBuffer
= '';
17815 * Handle key press events.
17818 * @param {jQuery.Event} e Key press event
17820 OO
.ui
.SelectWidget
.prototype.onKeyPress = function ( e
) {
17821 var c
, filter
, item
;
17823 if ( !e
.charCode
) {
17824 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
17825 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
17830 if ( String
.fromCodePoint
) {
17831 c
= String
.fromCodePoint( e
.charCode
);
17833 c
= String
.fromCharCode( e
.charCode
);
17836 if ( this.keyPressBufferTimer
) {
17837 clearTimeout( this.keyPressBufferTimer
);
17839 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
17841 item
= this.getHighlightedItem() || this.getSelectedItem();
17843 if ( this.keyPressBuffer
=== c
) {
17844 // Common (if weird) special case: typing "xxxx" will cycle through all
17845 // the items beginning with "x".
17847 item
= this.getRelativeSelectableItem( item
, 1 );
17850 this.keyPressBuffer
+= c
;
17853 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
17854 if ( !item
|| !filter( item
) ) {
17855 item
= this.getRelativeSelectableItem( item
, 1, filter
);
17858 if ( item
.constructor.static.highlightable
) {
17859 this.highlightItem( item
);
17861 this.chooseItem( item
);
17863 item
.scrollElementIntoView();
17870 * Get a matcher for the specific string
17873 * @param {string} s String to match against items
17874 * @param {boolean} [exact=false] Only accept exact matches
17875 * @return {Function} function ( OO.ui.OptionItem ) => boolean
17877 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
, exact
) {
17880 if ( s
.normalize
) {
17883 s
= exact
? s
.trim() : s
.replace( /^\s+/, '' );
17884 re
= '^\\s*' + s
.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
17888 re
= new RegExp( re
, 'i' );
17889 return function ( item
) {
17890 var l
= item
.getLabel();
17891 if ( typeof l
!== 'string' ) {
17892 l
= item
.$label
.text();
17894 if ( l
.normalize
) {
17897 return re
.test( l
);
17902 * Bind key press listener.
17906 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
17907 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler
);
17911 * Unbind key down listener.
17913 * If you override this, be sure to call this.clearKeyPressBuffer() from your
17918 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
17919 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler
);
17920 this.clearKeyPressBuffer();
17924 * Visibility change handler
17927 * @param {boolean} visible
17929 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
17931 this.clearKeyPressBuffer();
17936 * Get the closest item to a jQuery.Event.
17939 * @param {jQuery.Event} e
17940 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
17942 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
17943 return $( e
.target
).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
17947 * Get selected item.
17949 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
17951 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
17954 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
17955 if ( this.items
[ i
].isSelected() ) {
17956 return this.items
[ i
];
17963 * Get highlighted item.
17965 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
17967 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
17970 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
17971 if ( this.items
[ i
].isHighlighted() ) {
17972 return this.items
[ i
];
17979 * Toggle pressed state.
17981 * Press is a state that occurs when a user mouses down on an item, but
17982 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
17983 * until the user releases the mouse.
17985 * @param {boolean} pressed An option is being pressed
17987 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
17988 if ( pressed
=== undefined ) {
17989 pressed
= !this.pressed
;
17991 if ( pressed
!== this.pressed
) {
17993 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
17994 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
17995 this.pressed
= pressed
;
18000 * Highlight an option. If the `item` param is omitted, no options will be highlighted
18001 * and any existing highlight will be removed. The highlight is mutually exclusive.
18003 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
18007 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
18008 var i
, len
, highlighted
,
18011 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18012 highlighted
= this.items
[ i
] === item
;
18013 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
18014 this.items
[ i
].setHighlighted( highlighted
);
18019 this.emit( 'highlight', item
);
18026 * Fetch an item by its label.
18028 * @param {string} label Label of the item to select.
18029 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18030 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
18032 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
18033 var i
, item
, found
,
18034 len
= this.items
.length
,
18035 filter
= this.getItemMatcher( label
, true );
18037 for ( i
= 0; i
< len
; i
++ ) {
18038 item
= this.items
[ i
];
18039 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
18046 filter
= this.getItemMatcher( label
, false );
18047 for ( i
= 0; i
< len
; i
++ ) {
18048 item
= this.items
[ i
];
18049 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
18065 * Programmatically select an option by its label. If the item does not exist,
18066 * all options will be deselected.
18068 * @param {string} [label] Label of the item to select.
18069 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18073 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
18074 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
18075 if ( label
=== undefined || !itemFromLabel
) {
18076 return this.selectItem();
18078 return this.selectItem( itemFromLabel
);
18082 * Programmatically select an option by its data. If the `data` parameter is omitted,
18083 * or if the item does not exist, all options will be deselected.
18085 * @param {Object|string} [data] Value of the item to select, omit to deselect all
18089 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
18090 var itemFromData
= this.getItemFromData( data
);
18091 if ( data
=== undefined || !itemFromData
) {
18092 return this.selectItem();
18094 return this.selectItem( itemFromData
);
18098 * Programmatically select an option by its reference. If the `item` parameter is omitted,
18099 * all options will be deselected.
18101 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
18105 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
18106 var i
, len
, selected
,
18109 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18110 selected
= this.items
[ i
] === item
;
18111 if ( this.items
[ i
].isSelected() !== selected
) {
18112 this.items
[ i
].setSelected( selected
);
18117 this.emit( 'select', item
);
18126 * Press is a state that occurs when a user mouses down on an item, but has not
18127 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
18128 * releases the mouse.
18130 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
18134 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
18135 var i
, len
, pressed
,
18138 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18139 pressed
= this.items
[ i
] === item
;
18140 if ( this.items
[ i
].isPressed() !== pressed
) {
18141 this.items
[ i
].setPressed( pressed
);
18146 this.emit( 'press', item
);
18155 * Note that ‘choose’ should never be modified programmatically. A user can choose
18156 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
18157 * use the #selectItem method.
18159 * This method is identical to #selectItem, but may vary in subclasses that take additional action
18160 * when users choose an item with the keyboard or mouse.
18162 * @param {OO.ui.OptionWidget} item Item to choose
18166 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
18167 this.selectItem( item
);
18168 this.emit( 'choose', item
);
18174 * Get an option by its position relative to the specified item (or to the start of the option array,
18175 * if item is `null`). The direction in which to search through the option array is specified with a
18176 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
18177 * `null` if there are no options in the array.
18179 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
18180 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
18181 * @param {Function} filter Only consider items for which this function returns
18182 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
18183 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
18185 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
, filter
) {
18186 var currentIndex
, nextIndex
, i
,
18187 increase
= direction
> 0 ? 1 : -1,
18188 len
= this.items
.length
;
18190 if ( !$.isFunction( filter
) ) {
18191 filter
= OO
.ui
.SelectWidget
.static.passAllFilter
;
18194 if ( item
instanceof OO
.ui
.OptionWidget
) {
18195 currentIndex
= this.items
.indexOf( item
);
18196 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
18198 // If no item is selected and moving forward, start at the beginning.
18199 // If moving backward, start at the end.
18200 nextIndex
= direction
> 0 ? 0 : len
- 1;
18203 for ( i
= 0; i
< len
; i
++ ) {
18204 item
= this.items
[ nextIndex
];
18205 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
18208 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
18214 * Get the next selectable item or `null` if there are no selectable items.
18215 * Disabled options and menu-section markers and breaks are not selectable.
18217 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
18219 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
18222 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18223 item
= this.items
[ i
];
18224 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() ) {
18233 * Add an array of options to the select. Optionally, an index number can be used to
18234 * specify an insertion point.
18236 * @param {OO.ui.OptionWidget[]} items Items to add
18237 * @param {number} [index] Index to insert items after
18241 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
18243 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
18245 // Always provide an index, even if it was omitted
18246 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
18252 * Remove the specified array of options from the select. Options will be detached
18253 * from the DOM, not removed, so they can be reused later. To remove all options from
18254 * the select, you may wish to use the #clearItems method instead.
18256 * @param {OO.ui.OptionWidget[]} items Items to remove
18260 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
18263 // Deselect items being removed
18264 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
18266 if ( item
.isSelected() ) {
18267 this.selectItem( null );
18272 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
18274 this.emit( 'remove', items
);
18280 * Clear all options from the select. Options will be detached from the DOM, not removed,
18281 * so that they can be reused later. To remove a subset of options from the select, use
18282 * the #removeItems method.
18287 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
18288 var items
= this.items
.slice();
18291 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
18294 this.selectItem( null );
18296 this.emit( 'remove', items
);
18302 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
18303 * button options and is used together with
18304 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
18305 * highlighting, choosing, and selecting mutually exclusive options. Please see
18306 * the [OOjs UI documentation on MediaWiki] [1] for more information.
18309 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
18310 * var option1 = new OO.ui.ButtonOptionWidget( {
18312 * label: 'Option 1',
18313 * title: 'Button option 1'
18316 * var option2 = new OO.ui.ButtonOptionWidget( {
18318 * label: 'Option 2',
18319 * title: 'Button option 2'
18322 * var option3 = new OO.ui.ButtonOptionWidget( {
18324 * label: 'Option 3',
18325 * title: 'Button option 3'
18328 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
18329 * items: [ option1, option2, option3 ]
18331 * $( 'body' ).append( buttonSelect.$element );
18333 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18336 * @extends OO.ui.SelectWidget
18337 * @mixins OO.ui.mixin.TabIndexedElement
18340 * @param {Object} [config] Configuration options
18342 OO
.ui
.ButtonSelectWidget
= function OoUiButtonSelectWidget( config
) {
18343 // Parent constructor
18344 OO
.ui
.ButtonSelectWidget
.parent
.call( this, config
);
18346 // Mixin constructors
18347 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
18350 this.$element
.on( {
18351 focus
: this.bindKeyDownListener
.bind( this ),
18352 blur
: this.unbindKeyDownListener
.bind( this )
18356 this.$element
.addClass( 'oo-ui-buttonSelectWidget' );
18361 OO
.inheritClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.SelectWidget
);
18362 OO
.mixinClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
18365 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
18366 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
18367 * an interface for adding, removing and selecting options.
18368 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18370 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
18371 * OO.ui.RadioSelectInputWidget instead.
18374 * // A RadioSelectWidget with RadioOptions.
18375 * var option1 = new OO.ui.RadioOptionWidget( {
18377 * label: 'Selected radio option'
18380 * var option2 = new OO.ui.RadioOptionWidget( {
18382 * label: 'Unselected radio option'
18385 * var radioSelect=new OO.ui.RadioSelectWidget( {
18386 * items: [ option1, option2 ]
18389 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
18390 * radioSelect.selectItem( option1 );
18392 * $( 'body' ).append( radioSelect.$element );
18394 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18398 * @extends OO.ui.SelectWidget
18399 * @mixins OO.ui.mixin.TabIndexedElement
18402 * @param {Object} [config] Configuration options
18404 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
18405 // Parent constructor
18406 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
18408 // Mixin constructors
18409 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
18412 this.$element
.on( {
18413 focus
: this.bindKeyDownListener
.bind( this ),
18414 blur
: this.unbindKeyDownListener
.bind( this )
18419 .addClass( 'oo-ui-radioSelectWidget' )
18420 .attr( 'role', 'radiogroup' );
18425 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
18426 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
18429 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
18430 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
18431 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
18432 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
18433 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
18434 * and customized to be opened, closed, and displayed as needed.
18436 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
18437 * mouse outside the menu.
18439 * Menus also have support for keyboard interaction:
18441 * - Enter/Return key: choose and select a menu option
18442 * - Up-arrow key: highlight the previous menu option
18443 * - Down-arrow key: highlight the next menu option
18444 * - Esc key: hide the menu
18446 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18447 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18450 * @extends OO.ui.SelectWidget
18451 * @mixins OO.ui.mixin.ClippableElement
18454 * @param {Object} [config] Configuration options
18455 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
18456 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
18457 * and {@link OO.ui.mixin.LookupElement LookupElement}
18458 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
18459 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiSelectWidget CapsuleMultiSelectWidget}
18460 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
18461 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
18462 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
18463 * that button, unless the button (or its parent widget) is passed in here.
18464 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
18465 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
18467 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
18468 // Configuration initialization
18469 config
= config
|| {};
18471 // Parent constructor
18472 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
18474 // Mixin constructors
18475 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
18478 this.newItems
= null;
18479 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
18480 this.filterFromInput
= !!config
.filterFromInput
;
18481 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
18482 this.$widget
= config
.widget
? config
.widget
.$element
: null;
18483 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
18484 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
18488 .addClass( 'oo-ui-menuSelectWidget' )
18489 .attr( 'role', 'menu' );
18491 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
18492 // that reference properties not initialized at that time of parent class construction
18493 // TODO: Find a better way to handle post-constructor setup
18494 this.visible
= false;
18495 this.$element
.addClass( 'oo-ui-element-hidden' );
18500 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
18501 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
18506 * Handles document mouse down events.
18509 * @param {jQuery.Event} e Key down event
18511 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
18513 !OO
.ui
.contains( this.$element
[ 0 ], e
.target
, true ) &&
18514 ( !this.$widget
|| !OO
.ui
.contains( this.$widget
[ 0 ], e
.target
, true ) )
18516 this.toggle( false );
18523 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
18524 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
18526 if ( !this.isDisabled() && this.isVisible() ) {
18527 switch ( e
.keyCode
) {
18528 case OO
.ui
.Keys
.LEFT
:
18529 case OO
.ui
.Keys
.RIGHT
:
18530 // Do nothing if a text field is associated, arrow keys will be handled natively
18531 if ( !this.$input
) {
18532 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
18535 case OO
.ui
.Keys
.ESCAPE
:
18536 case OO
.ui
.Keys
.TAB
:
18537 if ( currentItem
) {
18538 currentItem
.setHighlighted( false );
18540 this.toggle( false );
18541 // Don't prevent tabbing away, prevent defocusing
18542 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
18543 e
.preventDefault();
18544 e
.stopPropagation();
18548 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
18555 * Update menu item visibility after input changes.
18558 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
18560 len
= this.items
.length
,
18561 showAll
= !this.isVisible(),
18562 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() );
18564 for ( i
= 0; i
< len
; i
++ ) {
18565 item
= this.items
[ i
];
18566 if ( item
instanceof OO
.ui
.OptionWidget
) {
18567 item
.toggle( showAll
|| filter( item
) );
18571 // Reevaluate clipping
18578 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
18579 if ( this.$input
) {
18580 this.$input
.on( 'keydown', this.onKeyDownHandler
);
18582 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyDownListener
.call( this );
18589 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
18590 if ( this.$input
) {
18591 this.$input
.off( 'keydown', this.onKeyDownHandler
);
18593 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyDownListener
.call( this );
18600 OO
.ui
.MenuSelectWidget
.prototype.bindKeyPressListener = function () {
18601 if ( this.$input
) {
18602 if ( this.filterFromInput
) {
18603 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
18606 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyPressListener
.call( this );
18613 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyPressListener = function () {
18614 if ( this.$input
) {
18615 if ( this.filterFromInput
) {
18616 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
18617 this.updateItemVisibility();
18620 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyPressListener
.call( this );
18627 * When a user chooses an item, the menu is closed.
18629 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
18630 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
18631 * @param {OO.ui.OptionWidget} item Item to choose
18634 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
18635 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
18636 this.toggle( false );
18643 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
18647 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
18650 if ( !this.newItems
) {
18651 this.newItems
= [];
18654 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
18656 if ( this.isVisible() ) {
18657 // Defer fitting label until item has been attached
18660 this.newItems
.push( item
);
18664 // Reevaluate clipping
18673 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
18675 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
18677 // Reevaluate clipping
18686 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
18688 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
18690 // Reevaluate clipping
18699 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
18700 var i
, len
, change
;
18702 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
18703 change
= visible
!== this.isVisible();
18706 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
18710 this.bindKeyDownListener();
18711 this.bindKeyPressListener();
18713 if ( this.newItems
&& this.newItems
.length
) {
18714 for ( i
= 0, len
= this.newItems
.length
; i
< len
; i
++ ) {
18715 this.newItems
[ i
].fitLabel();
18717 this.newItems
= null;
18719 this.toggleClipping( true );
18722 if ( this.autoHide
) {
18723 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler
);
18726 this.unbindKeyDownListener();
18727 this.unbindKeyPressListener();
18728 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler
);
18729 this.toggleClipping( false );
18737 * FloatingMenuSelectWidget is a menu that will stick under a specified
18738 * container, even when it is inserted elsewhere in the document (for example,
18739 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
18740 * menu from being clipped too aggresively.
18742 * The menu's position is automatically calculated and maintained when the menu
18743 * is toggled or the window is resized.
18745 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
18748 * @extends OO.ui.MenuSelectWidget
18751 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
18752 * Deprecated, omit this parameter and specify `$container` instead.
18753 * @param {Object} [config] Configuration options
18754 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
18756 OO
.ui
.FloatingMenuSelectWidget
= function OoUiFloatingMenuSelectWidget( inputWidget
, config
) {
18757 // Allow 'inputWidget' parameter and config for backwards compatibility
18758 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
18759 config
= inputWidget
;
18760 inputWidget
= config
.inputWidget
;
18763 // Configuration initialization
18764 config
= config
|| {};
18766 // Parent constructor
18767 OO
.ui
.FloatingMenuSelectWidget
.parent
.call( this, config
);
18770 this.inputWidget
= inputWidget
; // For backwards compatibility
18771 this.$container
= config
.$container
|| this.inputWidget
.$element
;
18772 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
18775 this.$element
.addClass( 'oo-ui-floatingMenuSelectWidget' );
18776 // For backwards compatibility
18777 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
18782 OO
.inheritClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
18784 // For backwards compatibility
18785 OO
.ui
.TextInputMenuSelectWidget
= OO
.ui
.FloatingMenuSelectWidget
;
18790 * Handle window resize event.
18793 * @param {jQuery.Event} e Window resize event
18795 OO
.ui
.FloatingMenuSelectWidget
.prototype.onWindowResize = function () {
18802 OO
.ui
.FloatingMenuSelectWidget
.prototype.toggle = function ( visible
) {
18804 visible
= visible
=== undefined ? !this.isVisible() : !!visible
;
18806 change
= visible
!== this.isVisible();
18808 if ( change
&& visible
) {
18809 // Make sure the width is set before the parent method runs.
18810 // After this we have to call this.position(); again to actually
18811 // position ourselves correctly.
18816 OO
.ui
.FloatingMenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
18819 if ( this.isVisible() ) {
18821 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
18823 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
18831 * Position the menu.
18836 OO
.ui
.FloatingMenuSelectWidget
.prototype.position = function () {
18837 var $container
= this.$container
,
18838 pos
= OO
.ui
.Element
.static.getRelativePosition( $container
, this.$element
.offsetParent() );
18840 // Position under input
18841 pos
.top
+= $container
.height();
18842 this.$element
.css( pos
);
18845 this.setIdealSize( $container
.width() );
18846 // We updated the position, so re-evaluate the clipping state
18853 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
18854 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
18856 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
18859 * @extends OO.ui.SelectWidget
18860 * @mixins OO.ui.mixin.TabIndexedElement
18863 * @param {Object} [config] Configuration options
18865 OO
.ui
.OutlineSelectWidget
= function OoUiOutlineSelectWidget( config
) {
18866 // Parent constructor
18867 OO
.ui
.OutlineSelectWidget
.parent
.call( this, config
);
18869 // Mixin constructors
18870 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
18873 this.$element
.on( {
18874 focus
: this.bindKeyDownListener
.bind( this ),
18875 blur
: this.unbindKeyDownListener
.bind( this )
18879 this.$element
.addClass( 'oo-ui-outlineSelectWidget' );
18884 OO
.inheritClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.SelectWidget
);
18885 OO
.mixinClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
18888 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
18890 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
18893 * @extends OO.ui.SelectWidget
18894 * @mixins OO.ui.mixin.TabIndexedElement
18897 * @param {Object} [config] Configuration options
18899 OO
.ui
.TabSelectWidget
= function OoUiTabSelectWidget( config
) {
18900 // Parent constructor
18901 OO
.ui
.TabSelectWidget
.parent
.call( this, config
);
18903 // Mixin constructors
18904 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
18907 this.$element
.on( {
18908 focus
: this.bindKeyDownListener
.bind( this ),
18909 blur
: this.unbindKeyDownListener
.bind( this )
18913 this.$element
.addClass( 'oo-ui-tabSelectWidget' );
18918 OO
.inheritClass( OO
.ui
.TabSelectWidget
, OO
.ui
.SelectWidget
);
18919 OO
.mixinClass( OO
.ui
.TabSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
18922 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
18923 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
18924 * (to adjust the value in increments) to allow the user to enter a number.
18927 * // Example: A NumberInputWidget.
18928 * var numberInput = new OO.ui.NumberInputWidget( {
18929 * label: 'NumberInputWidget',
18930 * input: { value: 5, min: 1, max: 10 }
18932 * $( 'body' ).append( numberInput.$element );
18935 * @extends OO.ui.Widget
18938 * @param {Object} [config] Configuration options
18939 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
18940 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
18941 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
18942 * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
18943 * @cfg {number} [min=-Infinity] Minimum allowed value
18944 * @cfg {number} [max=Infinity] Maximum allowed value
18945 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
18946 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
18948 OO
.ui
.NumberInputWidget
= function OoUiNumberInputWidget( config
) {
18949 // Configuration initialization
18950 config
= $.extend( {
18958 // Parent constructor
18959 OO
.ui
.NumberInputWidget
.parent
.call( this, config
);
18962 this.input
= new OO
.ui
.TextInputWidget( $.extend(
18964 disabled
: this.isDisabled()
18968 this.minusButton
= new OO
.ui
.ButtonWidget( $.extend(
18970 disabled
: this.isDisabled(),
18973 config
.minusButton
,
18975 classes
: [ 'oo-ui-numberInputWidget-minusButton' ],
18979 this.plusButton
= new OO
.ui
.ButtonWidget( $.extend(
18981 disabled
: this.isDisabled(),
18986 classes
: [ 'oo-ui-numberInputWidget-plusButton' ],
18992 this.input
.connect( this, {
18993 change
: this.emit
.bind( this, 'change' ),
18994 enter
: this.emit
.bind( this, 'enter' )
18996 this.input
.$input
.on( {
18997 keydown
: this.onKeyDown
.bind( this ),
18998 'wheel mousewheel DOMMouseScroll': this.onWheel
.bind( this )
19000 this.plusButton
.connect( this, {
19001 click
: [ 'onButtonClick', +1 ]
19003 this.minusButton
.connect( this, {
19004 click
: [ 'onButtonClick', -1 ]
19008 this.setIsInteger( !!config
.isInteger
);
19009 this.setRange( config
.min
, config
.max
);
19010 this.setStep( config
.step
, config
.pageStep
);
19012 this.$field
= $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
19014 this.minusButton
.$element
,
19015 this.input
.$element
,
19016 this.plusButton
.$element
19018 this.$element
.addClass( 'oo-ui-numberInputWidget' ).append( this.$field
);
19019 this.input
.setValidation( this.validateNumber
.bind( this ) );
19024 OO
.inheritClass( OO
.ui
.NumberInputWidget
, OO
.ui
.Widget
);
19029 * A `change` event is emitted when the value of the input changes.
19035 * An `enter` event is emitted when the user presses 'enter' inside the text box.
19043 * Set whether only integers are allowed
19044 * @param {boolean} flag
19046 OO
.ui
.NumberInputWidget
.prototype.setIsInteger = function ( flag
) {
19047 this.isInteger
= !!flag
;
19048 this.input
.setValidityFlag();
19052 * Get whether only integers are allowed
19053 * @return {boolean} Flag value
19055 OO
.ui
.NumberInputWidget
.prototype.getIsInteger = function () {
19056 return this.isInteger
;
19060 * Set the range of allowed values
19061 * @param {number} min Minimum allowed value
19062 * @param {number} max Maximum allowed value
19064 OO
.ui
.NumberInputWidget
.prototype.setRange = function ( min
, max
) {
19066 throw new Error( 'Minimum (' + min
+ ') must not be greater than maximum (' + max
+ ')' );
19070 this.input
.setValidityFlag();
19074 * Get the current range
19075 * @return {number[]} Minimum and maximum values
19077 OO
.ui
.NumberInputWidget
.prototype.getRange = function () {
19078 return [ this.min
, this.max
];
19082 * Set the stepping deltas
19083 * @param {number} step Normal step
19084 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
19086 OO
.ui
.NumberInputWidget
.prototype.setStep = function ( step
, pageStep
) {
19088 throw new Error( 'Step value must be positive' );
19090 if ( pageStep
=== null ) {
19091 pageStep
= step
* 10;
19092 } else if ( pageStep
<= 0 ) {
19093 throw new Error( 'Page step value must be positive' );
19096 this.pageStep
= pageStep
;
19100 * Get the current stepping values
19101 * @return {number[]} Step and page step
19103 OO
.ui
.NumberInputWidget
.prototype.getStep = function () {
19104 return [ this.step
, this.pageStep
];
19108 * Get the current value of the widget
19111 OO
.ui
.NumberInputWidget
.prototype.getValue = function () {
19112 return this.input
.getValue();
19116 * Get the current value of the widget as a number
19117 * @return {number} May be NaN, or an invalid number
19119 OO
.ui
.NumberInputWidget
.prototype.getNumericValue = function () {
19120 return +this.input
.getValue();
19124 * Set the value of the widget
19125 * @param {string} value Invalid values are allowed
19127 OO
.ui
.NumberInputWidget
.prototype.setValue = function ( value
) {
19128 this.input
.setValue( value
);
19132 * Adjust the value of the widget
19133 * @param {number} delta Adjustment amount
19135 OO
.ui
.NumberInputWidget
.prototype.adjustValue = function ( delta
) {
19136 var n
, v
= this.getNumericValue();
19139 if ( isNaN( delta
) || !isFinite( delta
) ) {
19140 throw new Error( 'Delta must be a finite number' );
19143 if ( isNaN( v
) ) {
19147 n
= Math
.max( Math
.min( n
, this.max
), this.min
);
19148 if ( this.isInteger
) {
19149 n
= Math
.round( n
);
19154 this.setValue( n
);
19161 * @param {string} value Field value
19162 * @return {boolean}
19164 OO
.ui
.NumberInputWidget
.prototype.validateNumber = function ( value
) {
19166 if ( isNaN( n
) || !isFinite( n
) ) {
19170 /*jshint bitwise: false */
19171 if ( this.isInteger
&& ( n
| 0 ) !== n
) {
19174 /*jshint bitwise: true */
19176 if ( n
< this.min
|| n
> this.max
) {
19184 * Handle mouse click events.
19187 * @param {number} dir +1 or -1
19189 OO
.ui
.NumberInputWidget
.prototype.onButtonClick = function ( dir
) {
19190 this.adjustValue( dir
* this.step
);
19194 * Handle mouse wheel events.
19197 * @param {jQuery.Event} event
19199 OO
.ui
.NumberInputWidget
.prototype.onWheel = function ( event
) {
19202 // Standard 'wheel' event
19203 if ( event
.originalEvent
.deltaMode
!== undefined ) {
19204 this.sawWheelEvent
= true;
19206 if ( event
.originalEvent
.deltaY
) {
19207 delta
= -event
.originalEvent
.deltaY
;
19208 } else if ( event
.originalEvent
.deltaX
) {
19209 delta
= event
.originalEvent
.deltaX
;
19212 // Non-standard events
19213 if ( !this.sawWheelEvent
) {
19214 if ( event
.originalEvent
.wheelDeltaX
) {
19215 delta
= -event
.originalEvent
.wheelDeltaX
;
19216 } else if ( event
.originalEvent
.wheelDeltaY
) {
19217 delta
= event
.originalEvent
.wheelDeltaY
;
19218 } else if ( event
.originalEvent
.wheelDelta
) {
19219 delta
= event
.originalEvent
.wheelDelta
;
19220 } else if ( event
.originalEvent
.detail
) {
19221 delta
= -event
.originalEvent
.detail
;
19226 delta
= delta
< 0 ? -1 : 1;
19227 this.adjustValue( delta
* this.step
);
19234 * Handle key down events.
19238 * @param {jQuery.Event} e Key down event
19240 OO
.ui
.NumberInputWidget
.prototype.onKeyDown = function ( e
) {
19241 if ( !this.isDisabled() ) {
19242 switch ( e
.which
) {
19243 case OO
.ui
.Keys
.UP
:
19244 this.adjustValue( this.step
);
19246 case OO
.ui
.Keys
.DOWN
:
19247 this.adjustValue( -this.step
);
19249 case OO
.ui
.Keys
.PAGEUP
:
19250 this.adjustValue( this.pageStep
);
19252 case OO
.ui
.Keys
.PAGEDOWN
:
19253 this.adjustValue( -this.pageStep
);
19262 OO
.ui
.NumberInputWidget
.prototype.setDisabled = function ( disabled
) {
19264 OO
.ui
.NumberInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
19266 if ( this.input
) {
19267 this.input
.setDisabled( this.isDisabled() );
19269 if ( this.minusButton
) {
19270 this.minusButton
.setDisabled( this.isDisabled() );
19272 if ( this.plusButton
) {
19273 this.plusButton
.setDisabled( this.isDisabled() );
19280 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
19281 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
19282 * visually by a slider in the leftmost position.
19285 * // Toggle switches in the 'off' and 'on' position.
19286 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
19287 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
19291 * // Create a FieldsetLayout to layout and label switches
19292 * var fieldset = new OO.ui.FieldsetLayout( {
19293 * label: 'Toggle switches'
19295 * fieldset.addItems( [
19296 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
19297 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
19299 * $( 'body' ).append( fieldset.$element );
19302 * @extends OO.ui.ToggleWidget
19303 * @mixins OO.ui.mixin.TabIndexedElement
19306 * @param {Object} [config] Configuration options
19307 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
19308 * By default, the toggle switch is in the 'off' position.
19310 OO
.ui
.ToggleSwitchWidget
= function OoUiToggleSwitchWidget( config
) {
19311 // Parent constructor
19312 OO
.ui
.ToggleSwitchWidget
.parent
.call( this, config
);
19314 // Mixin constructors
19315 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
19318 this.dragging
= false;
19319 this.dragStart
= null;
19320 this.sliding
= false;
19321 this.$glow
= $( '<span>' );
19322 this.$grip
= $( '<span>' );
19325 this.$element
.on( {
19326 click
: this.onClick
.bind( this ),
19327 keypress
: this.onKeyPress
.bind( this )
19331 this.$glow
.addClass( 'oo-ui-toggleSwitchWidget-glow' );
19332 this.$grip
.addClass( 'oo-ui-toggleSwitchWidget-grip' );
19334 .addClass( 'oo-ui-toggleSwitchWidget' )
19335 .attr( 'role', 'checkbox' )
19336 .append( this.$glow
, this.$grip
);
19341 OO
.inheritClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.ToggleWidget
);
19342 OO
.mixinClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.mixin
.TabIndexedElement
);
19347 * Handle mouse click events.
19350 * @param {jQuery.Event} e Mouse click event
19352 OO
.ui
.ToggleSwitchWidget
.prototype.onClick = function ( e
) {
19353 if ( !this.isDisabled() && e
.which
=== 1 ) {
19354 this.setValue( !this.value
);
19360 * Handle key press events.
19363 * @param {jQuery.Event} e Key press event
19365 OO
.ui
.ToggleSwitchWidget
.prototype.onKeyPress = function ( e
) {
19366 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
19367 this.setValue( !this.value
);
19373 * Deprecated aliases for classes in the `OO.ui.mixin` namespace.
19377 * @inheritdoc OO.ui.mixin.ButtonElement
19378 * @deprecated Use {@link OO.ui.mixin.ButtonElement} instead.
19380 OO
.ui
.ButtonElement
= OO
.ui
.mixin
.ButtonElement
;
19383 * @inheritdoc OO.ui.mixin.ClippableElement
19384 * @deprecated Use {@link OO.ui.mixin.ClippableElement} instead.
19386 OO
.ui
.ClippableElement
= OO
.ui
.mixin
.ClippableElement
;
19389 * @inheritdoc OO.ui.mixin.DraggableElement
19390 * @deprecated Use {@link OO.ui.mixin.DraggableElement} instead.
19392 OO
.ui
.DraggableElement
= OO
.ui
.mixin
.DraggableElement
;
19395 * @inheritdoc OO.ui.mixin.DraggableGroupElement
19396 * @deprecated Use {@link OO.ui.mixin.DraggableGroupElement} instead.
19398 OO
.ui
.DraggableGroupElement
= OO
.ui
.mixin
.DraggableGroupElement
;
19401 * @inheritdoc OO.ui.mixin.FlaggedElement
19402 * @deprecated Use {@link OO.ui.mixin.FlaggedElement} instead.
19404 OO
.ui
.FlaggedElement
= OO
.ui
.mixin
.FlaggedElement
;
19407 * @inheritdoc OO.ui.mixin.GroupElement
19408 * @deprecated Use {@link OO.ui.mixin.GroupElement} instead.
19410 OO
.ui
.GroupElement
= OO
.ui
.mixin
.GroupElement
;
19413 * @inheritdoc OO.ui.mixin.GroupWidget
19414 * @deprecated Use {@link OO.ui.mixin.GroupWidget} instead.
19416 OO
.ui
.GroupWidget
= OO
.ui
.mixin
.GroupWidget
;
19419 * @inheritdoc OO.ui.mixin.IconElement
19420 * @deprecated Use {@link OO.ui.mixin.IconElement} instead.
19422 OO
.ui
.IconElement
= OO
.ui
.mixin
.IconElement
;
19425 * @inheritdoc OO.ui.mixin.IndicatorElement
19426 * @deprecated Use {@link OO.ui.mixin.IndicatorElement} instead.
19428 OO
.ui
.IndicatorElement
= OO
.ui
.mixin
.IndicatorElement
;
19431 * @inheritdoc OO.ui.mixin.ItemWidget
19432 * @deprecated Use {@link OO.ui.mixin.ItemWidget} instead.
19434 OO
.ui
.ItemWidget
= OO
.ui
.mixin
.ItemWidget
;
19437 * @inheritdoc OO.ui.mixin.LabelElement
19438 * @deprecated Use {@link OO.ui.mixin.LabelElement} instead.
19440 OO
.ui
.LabelElement
= OO
.ui
.mixin
.LabelElement
;
19443 * @inheritdoc OO.ui.mixin.LookupElement
19444 * @deprecated Use {@link OO.ui.mixin.LookupElement} instead.
19446 OO
.ui
.LookupElement
= OO
.ui
.mixin
.LookupElement
;
19449 * @inheritdoc OO.ui.mixin.PendingElement
19450 * @deprecated Use {@link OO.ui.mixin.PendingElement} instead.
19452 OO
.ui
.PendingElement
= OO
.ui
.mixin
.PendingElement
;
19455 * @inheritdoc OO.ui.mixin.PopupElement
19456 * @deprecated Use {@link OO.ui.mixin.PopupElement} instead.
19458 OO
.ui
.PopupElement
= OO
.ui
.mixin
.PopupElement
;
19461 * @inheritdoc OO.ui.mixin.TabIndexedElement
19462 * @deprecated Use {@link OO.ui.mixin.TabIndexedElement} instead.
19464 OO
.ui
.TabIndexedElement
= OO
.ui
.mixin
.TabIndexedElement
;
19467 * @inheritdoc OO.ui.mixin.TitledElement
19468 * @deprecated Use {@link OO.ui.mixin.TitledElement} instead.
19470 OO
.ui
.TitledElement
= OO
.ui
.mixin
.TitledElement
;